두 문자열이 서로의 아나그램인지 확인하는 방법

두 문자열이 서로의 아나그램인지 확인하는 방법

아나그램은 다른 문자열의 문자를 재배열하여 형성된 문자열입니다. 두 문자열이 서로의 아나그램인지 확인하는 것이 어렵게 들릴 수 있지만 약간 까다롭고 믿을 수 없을 정도로 간단합니다. 이 기사에서는 C++, Python 및 JavaScript를 사용하여 두 문자열이 서로의 아나그램인지 확인하는 방법을 배웁니다.





문제 설명

두 개의 문자열 s1과 s2가 주어지면 두 문자열이 서로의 아나그램인지 여부를 확인해야 합니다.





실시예 1 : s1 = '창의적', s2 = '반응적'이라고 합시다.





두 번째 문자열은 첫 번째 문자열의 문자를 재배열하여 구성할 수 있고 그 반대도 가능하므로 두 문자열은 서로의 아나그램입니다.

실시예 2 : s1 = 'Peter Piper가 절인 고추 한 펙을 골랐다' 및 s2 = 'Peter Piper가 고른 절인 고추 한 펙'이라고 가정합니다.



두 번째 문자열은 첫 번째 문자열의 문자를 재배열하여 구성할 수 없고 그 반대의 경우도 마찬가지이므로 두 문자열은 서로의 아나그램이 아닙니다.

두 문자열이 서로의 아나그램인지 확인하는 프로세스

아래 접근 방식에 따라 두 문자열이 서로의 아나그램인지 확인할 수 있습니다.





  1. 두 문자열의 길이를 비교합니다.
  2. 두 문자열의 길이가 같지 않으면 서로의 아나그램이 될 수 없음을 의미합니다. 따라서 false를 반환합니다.
  3. 두 문자열의 길이가 같으면 계속 진행합니다.
  4. 두 문자열을 모두 정렬합니다.
  5. 두 정렬된 문자열을 비교합니다.
  6. 정렬된 두 문자열이 모두 같으면 서로의 아나그램임을 의미합니다. 따라서 true를 반환합니다.
  7. 정렬된 두 문자열이 모두 다르면 서로의 아나그램이 아니라는 의미입니다. 따라서 false를 반환합니다.

관련된: 문자열이 회문인지 확인하는 방법

두 문자열이 서로의 아나그램인지 확인하는 C++ 프로그램

다음은 두 문자열이 서로의 아나그램인지 여부를 확인하는 C++ 프로그램입니다.





#include
using namespace std;
bool checkAnagrams(string s1, string s2)
{
int size1 = s1.length();
int size2 = s2.length();
// If the length of both strings are not the same,
// it means they can't be anagrams of each other.
// Thus, return false.
if (size1 != size2)
{
return false;
}
sort(s1.begin(), s1.end());
sort(s2.begin(), s2.end());
for (int i = 0; i {
if (s1[i] != s2[i])
{
return false;
}
}
return true;
}
int main()
{
string s1 = 'listen';
string s2 = 'silent';
cout << 'String 1: ' << s1 << endl;
cout << 'String 2: ' << s2 << endl;
if(checkAnagrams(s1, s2))
{
cout << 'Yes, the two strings are anagrams of each other' << endl;
}
else
{
cout << 'No, the two strings are not anagrams of each other' << endl;
}
string s3 = 'Welcome to MUO';
string s4 = 'MUO to Welcome';
cout << 'String 3: ' << s3 << endl;
cout << 'String 4: ' << s4 << endl;
if(checkAnagrams(s3, s4))
{
cout << 'Yes, the two strings are anagrams of each other' << endl;
}
else
{
cout << 'No, the two strings are not anagrams of each other' << endl;
}
string s5 = 'Peter Piper picked a peck of pickled peppers';
string s6 = 'A peck of pickled peppers Peter Piper picked';
cout << 'String 5: ' << s5 << endl;
cout << 'String 6: ' << s6 << endl;
if(checkAnagrams(s5, s6))
{
cout << 'Yes, the two strings are anagrams of each other' << endl;
}
else
{
cout << 'No, the two strings are not anagrams of each other' << endl;
}
string s7 = 'She sells seashells by the seashore';
string s8 = 'seashells by the seashore';
cout << 'String 7: ' << s7 << endl;
cout << 'String 8: ' << s8 << endl;
if(checkAnagrams(s7, s8))
{
cout << 'Yes, the two strings are anagrams of each other' << endl;
}
else
{
cout << 'No, the two strings are not anagrams of each other' << endl;
}
string s9 = 'creative';
string s10 = 'reactive';
cout << 'String 9: ' << s9 << endl;
cout << 'String 10: ' << s10 << endl;
if(checkAnagrams(s9, s10))
{
cout << 'Yes, the two strings are anagrams of each other' << endl;
}
else
{
cout << 'No, the two strings are not anagrams of each other' << endl;
}
return 0;
}

산출:

String 1: listen
String 2: silent
Yes, the two strings are anagrams of each other
String 3: Welcome to MUO
String 4: MUO to Welcome
Yes, the two strings are anagrams of each other
String 5: Peter Piper picked a peck of pickled peppers
String 6: A peck of pickled peppers Peter Piper picked
No, the two strings are not anagrams of each other
String 7: She sells seashells by the seashore
String 8: seashells by the seashore
No, the two strings are not anagrams of each other
String 9: creative
String 10: reactive
Yes, the two strings are anagrams of each other

관련 항목: 문자열에서 주어진 문자의 발생 횟수를 계산하는 방법

두 문자열이 서로의 아나그램인지 확인하는 Python 프로그램

다음은 두 문자열이 서로의 아나그램인지 확인하는 Python 프로그램입니다.

def checkAnagrams(s1, s2):
size1 = len(s1)
size2 = len(s2)
# If the length of both strings are not the same,
# it means they can't be anagrams of each other.
# Thus, return false.
if size1 != size2:
return 0
s1 = sorted(s1)
s2 = sorted(s2)
for i in range(0, size1):
if s1[i] != s2[i]:
return False
return True

s1 = 'listen'
s2 = 'silent'
print('String 1: ', s1)
print('String 2: ', s2)
if(checkAnagrams(s1, s2)):
print('Yes, the two strings are anagrams of each other')
else:
print('No, the two strings are not anagrams of each other')
s3 = 'Welcome to MUO'
s4 = 'MUO to Welcome'
print('String 3: ', s3)
print('String 4: ', s4)
if(checkAnagrams(s3, s4)):
print('Yes, the two strings are anagrams of each other')
else:
print('No, the two strings are not anagrams of each other')
s5 = 'Peter Piper picked a peck of pickled peppers'
s6 = 'A peck of pickled peppers Peter Piper picked'
print('String 5: ', s5)
print('String 6: ', s6)
if(checkAnagrams(s5, s6)):
print('Yes, the two strings are anagrams of each other')
else:
print('No, the two strings are not anagrams of each other')
s7 = 'She sells seashells by the seashore'
s8 = 'seashells by the seashore'
print('String 7: ', s7)
print('String 8: ', s8)
if(checkAnagrams(s7, s8)):
print('Yes, the two strings are anagrams of each other')
else:
print('No, the two strings are not anagrams of each other')
s9 = 'creative'
s10 = 'reactive'
print('String 9: ', s9)
print('String 10: ', s10)
if(checkAnagrams(s9, s10)):
print('Yes, the two strings are anagrams of each other')
else:
print('No, the two strings are not anagrams of each other')

산출:

String 1: listen
String 2: silent
Yes, the two strings are anagrams of each other
String 3: Welcome to MUO
String 4: MUO to Welcome
Yes, the two strings are anagrams of each other
String 5: Peter Piper picked a peck of pickled peppers
String 6: A peck of pickled peppers Peter Piper picked
No, the two strings are not anagrams of each other
String 7: She sells seashells by the seashore
String 8: seashells by the seashore
No, the two strings are not anagrams of each other
String 9: creative
String 10: reactive
Yes, the two strings are anagrams of each other

관련: 문자열에서 모음, 자음, 숫자 및 특수 문자를 찾는 방법

JavaScript에서 두 문자열이 서로의 아나그램인지 확인

다음은 두 문자열이 서로의 아나그램인지 여부를 확인하는 JavaScript 프로그램입니다.

function checkAnagrams(s1, s2) {
let size1 = s1.length;
let size2 = s2.length;
// If the length of both strings are not the same,
// it means they can't be anagrams of each other.
// Thus, return false.
if (size1 != size2)
{
return false;
}
s1.sort();
s2.sort();
for (let i = 0; i {
if (s1[i] != s2[i])
{
return false;
}
}
return true;
}

var s1 = 'listen';
var s2 = 'silent';
document.write('String 1: ' + s1 + '
');
document.write('String 2: ' + s2 + '
');
if(checkAnagrams(s1.split(''), s2.split(''))) {
document.write('Yes, the two strings are anagrams of each other' + '
');
} else {
document.write('No, the two strings are not anagrams of each other' + '
');
}
var s3 = 'Welcome to MUO';
var s4 = 'MUO to Welcome';
document.write('String 3: ' + s3 + '
');
document.write('String 4: ' + s4 + '
');
if(checkAnagrams(s3.split(''), s4.split(''))) {
document.write('Yes, the two strings are anagrams of each other' + '
');
} else {
document.write('No, the two strings are not anagrams of each other' + '
');
}
var s5 = 'Peter Piper picked a peck of pickled peppers';
var s6 = 'A peck of pickled peppers Peter Piper picked';
document.write('String 5: ' + s5 + '
');
document.write('String 6: ' + s6 + '
');
if(checkAnagrams(s5.split(''), s6.split(''))) {
document.write('Yes, the two strings are anagrams of each other' + '
');
} else {
document.write('No, the two strings are not anagrams of each other' + '
');
}
var s7 = 'She sells seashells by the seashore';
var s8 = 'seashells by the seashore';
document.write('String 7: ' + s7 + '
');
document.write('String 8: ' + s8 + '
');
if(checkAnagrams(s7.split(''), s8.split(''))) {
document.write('Yes, the two strings are anagrams of each other' + '
');
} else {
document.write('No, the two strings are not anagrams of each other' + '
');
}
var s9 = 'creative';
var s10 = 'reactive';
document.write('String 9: ' + s9 + '
');
document.write('String 10: ' + s10 + '
');
if(checkAnagrams(s9.split(''), s10.split(''))) {
document.write('Yes, the two strings are anagrams of each other' + '
');
} else {
document.write('No, the two strings are not anagrams of each other' + '
');
}

산출:

String 1: listen
String 2: silent
Yes, the two strings are anagrams of each other
String 3: Welcome to MUO
String 4: MUO to Welcome
Yes, the two strings are anagrams of each other
String 5: Peter Piper picked a peck of pickled peppers
String 6: A peck of pickled peppers Peter Piper picked
No, the two strings are not anagrams of each other
String 7: She sells seashells by the seashore
String 8: seashells by the seashore
No, the two strings are not anagrams of each other
String 9: creative
String 10: reactive
Yes, the two strings are anagrams of each other

관련된: 문자의 ASCII 값을 찾는 방법은 무엇입니까?

올바른 리소스를 사용하여 코딩 배우기

코딩 기술을 강화하려는 경우 새로운 개념을 배우고 사용하는 데 시간을 보내는 것이 중요합니다. 이를 수행하는 한 가지 방법은 프로그래밍 앱을 사용하는 것인데, 이는 동시에 재미를 느끼면서 다양한 프로그래밍 개념을 배우는 데 도움이 됩니다.

공유하다 공유하다 트위터 이메일 국제 프로그래머의 날을 위한 코딩 학습에 도움이 되는 8가지 앱

코딩 기술을 연마하고 싶으십니까? 이 앱과 웹사이트는 자신의 속도로 프로그래밍을 배우는 데 도움이 됩니다.

삭제 된 페이스 북 메시지를 복구하는 방법이 있습니까?
다음 읽기 관련 항목
  • 프로그램 작성
  • 자바스크립트
  • 파이썬
  • C 프로그래밍
저자 소개 유브라지 찬드라(60편 게재)

Yuvraj는 인도 델리 대학교의 컴퓨터 공학 학부생입니다. 그는 풀 스택 웹 개발에 열정적입니다. 그는 글을 쓰지 않을 때 다양한 기술의 깊이를 탐구하고 있습니다.

유브라지 찬드라가 참여한 작품 더보기

뉴스레터 구독

기술 팁, 리뷰, 무료 전자책 및 독점 거래에 대한 뉴스레터에 가입하십시오!

구독하려면 여기를 클릭하세요.