문제 설명
머쓱이는 태어난 지 11개월 된 조카를 돌보고 있습니다. 조카는 아직 "aya", "ye", "woo", "ma" 네 가지 발음과 네 가지 발음을 조합해서 만들 수 있는 발음밖에 하지 못하고 연속해서 같은 발음을 하는 것을 어려워합니다. 문자열 배열 babbling이 매개변수로 주어질 때, 머쓱이의 조카가 발음할 수 있는 단어의 개수를 return하도록 solution 함수를 완성해주세요.
문제 유형
- 패턴 매칭
코드 작성
#include <string>
#include <vector>
#include <map>
using namespace std;
int solution(vector<string> babbling) {
int answer = 0;
map<char, string> map =
{
{'a', "aya"},
{'y', "ye"},
{'w', "woo"},
{'m', "ma"}
};
for (int i = 0; i < babbling.size(); i++)
{
string str = babbling[i];
int matchedCount = 0;
char prevCh = 0;
for (int j = 0; j < str.size(); j++)
{
char ch = str[j];
auto it = map.find(ch);
if (it != map.end())
{
int bablingSize = it->second.size();
string temp = str.substr(j, bablingSize);
if (temp == it->second)
{
if (prevCh != it->first)
{
matchedCount += bablingSize;
j += bablingSize - 1;
prevCh = it->first;
}
else
{
break;
}
}
else
{
break;
}
}
else
{
break;
}
}
if (matchedCount == str.size())
answer++;
}
return answer;
}
- 코드의 가독성이 떨어진다.
다른 사람 풀이
#include <string>
#include <vector>
using namespace std;
int solution(vector<string> babbling) {
int answer = 0;
for(int i;i<babbling.size();i++)
{
string temp1="";
string temp2="";
for(char c:babbling[i])
{
temp1+=c;
if(temp1 == "aya"||temp1 == "ye"||temp1 == "woo"||temp1 == "ma")
{
if(temp2 == temp1) break;
temp2=temp1;
temp1="";
}
}
if(temp1.size()==0) answer++;
}
return answer;
}
- 발음할 문자열을 순회하면서 temp에 문자를 추가해 나간다.
- 발음할 문자열이 동일하면 temp를 비운다.
- 최종적으로 temp 사이즈가 비어있다면 카운트를 증가시킨다.