6996(애너그램)

최명수·2021년 1월 13일

6996번
#include <stdio.h>
#include <string.h>

int main()
{
int t,i,j,index=0,len=0,len2=0,count=0,max=0,k=0;
char str[102]={0, },str2[102]={0, },str3[102]={0, };
scanf("%d", &t);

//총 t번만큼 문자열을 받는다
for(i=0; i<t; i++)
{
    count=0,index=0,len=0;
    str[102]={0,},str2[102]={0,},str3[102]={0,};
    scanf(" %[^\n]s", &str);       
    len=strlen(str);
    for(j=0; j<len; j++)
    {
        if(str[j]==' ')
        {
            index=j;
        }
    }

    for(j=0; j<index; j++)
    {
        for(k=index+1; k<len; k++)
        {
            if(str[j]==str[k])
            {
                count++;
                break;
            }
        }
    }
    for(int t=0; t<index; t++)
    {
    	str2[t]=str[t];
	}
	k=0;
	for(j=index+1; j<len; j++)
	{
		str3[k++]=str[j];
		
	}
    printf("%d\n%d\n%d\n", index,len,count);
    if(count==index)
    {
        printf("%s & %s are anagrams.\n", str2,str3);
    } 
    else
    {
        printf("%s & %s are NOT anagrams.\n", str2,str3);
    }        

    
}
 
 
return 0;

}
처음에 c언어 이코드로 해결을 할려고했으나 str[j]랑str[k]랑 비교해가며 j에서의 문자가 k에있으면 count++를 해주었으나 k에 같은 문자가 여러개있으면 count가 이상한 값이 되어버림.
따라서 이코드로는 더이상 할수 없다고 판단함.
그래서 문자열은 c++로 해결하는게 더 편리해서 한번 c++로 풀어봄
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;
int main()
{
int t,i,j,index=0,len=0,len2=0,count=0,max=0,k=0;
string str,str2;
cin>>t;

//총 t번만큼 문자열을 받는다
cin.ignore();
for(i=0; i<t; i++)
{
    string a,b,c,d;
    cin>>a>>b;
    c=a;
    d=b;
    sort(a.begin(),a.end());
    sort(b.begin(),b.end());
    
    if(a==b)
    {
    	cout<<c<<" & "<<d<<" are "<<"anagrams.";
	}
	else
	{
		cout<<c<<" & "<<d<<" are NOT "<<"anagrams.";
	}
    if(i!=t-1)
    {
    	cout<<endl;
	}
}
 
 
return 0;

}
a와 b를 cin으로받음(a와b에공백이없기때문에getline()사용안함) 그리고 sort를 이용해 a와 b의 문자열을 a부터 정렬함 그리고 a와b를 비교해서 두문자열이 같으면 애너그램이다. 라고 생각함

0개의 댓글