강의

멘토링

커뮤니티

Inflearn Community Q&A

No author

This post's author information has been deleted.

Introduction to Algorithm Problem Solving for IT Employment (with C/C++): Coding Test Preparation

16. Anagram (Google Interview Question)

제가 직접 짠 코드에서 16번문제 4번에서만 오류가 납니다.

Resolved

Written on

·

303

0

이상하게 4번에서만 오류가 나서 반례가 있는지 계속 생각해봤는데 생각이 잘 안되서 질문드립니다!

aRes 는 a의 해당 a[i]번 값의 갯수를 저장하고 bRes는 b의 해당 b[j]번 값을 저장합니다. 그리고 그 값이 같을때 

flag를 flase로 해줍니다. 

c++ 에서도 강사님과 같은 방법을 써야하나요? 제 코드와 차이점이 뭔가요? 시간 측면에서 더 효율적인건가요?

#include 
#include 

int main(){
	using namespace std;
	//freopen("input.txt", "rt", stdin);
	string a,b;
	int i,j;
	int aRes,bRes;
	bool flag=true;
	cin>>a>>b;
	if(a.length()==b.length()){
		flag=true;
		for(i=0; i<a.length(); i++){
			aRes=1,bRes=1;
			for(j=0;j<a.length();j++){
				if(a[i]==b[j])
					bRes++;
					
			}
			for(j=i+1;j<a.length();j++){
				if(a[i]==a[j]){
					aRes++;
				}
			}
			if(aRes!=bRes) flag=false;	
		}
			if(flag) cout<<"NO";
			else cout<<"YES";
	}
	return 0;	
}
C++코테 준비 같이 해요!

Answer 2

1

codingcamp님의 프로필 이미지
codingcamp
Instructor

아래 코드로 수정하니 100점 나옵니다.

#include<bits/stdc++.h>
using namespace std;
int main(){
	using namespace std;
	//freopen("input.txt", "rt", stdin);
	string a,b;
	int i,j;
	int aRes,bRes;
	bool flag=true;
	cin>>a>>b;
	if(a.length()==b.length()){
		flag=true;
		for(i=0; i<a.length(); i++){
			aRes=0,bRes=0;
			for(j=0;j<a.length();j++){
				if(a[i]==b[j])
					bRes++;					
			}
			for(j=0;j<a.length();j++){
				if(a[i]==a[j]){
					aRes++;
				}
			}
			if(aRes!=bRes) flag=false;	
		}
			if(flag) cout<<"YES";
			else cout<<"NO";
	}
	return 0;	
}

0

제가 이상하게 생각했네요...ㅠㅠ 감사합니다!!

No author

This post's author information has been deleted.

Ask a question