첫 접근이 어려웠지만, 나름 잘 풀었다고 생각했던 문제가 있었다.
문자를 하나씩 검사하면서 앞에 같은 글자가 나왔는지, 나왔으면 몇 번째 앞인지를 배열에 담아 반환하는 문제였다.
나는 2차원 벡터를 사용해서 풀었다.
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> solution(string s) {
vector<int> answer;
vector<vector<int>> count(26, vector<int>(2,0)); // 여기에 a부터 z까지 나온 (현재 인덱스정보, 횟수)
int i =0;
for(auto c: s)
{
//만약 이미 1이 있으면, 몇 칸 앞에 같은 문자가 있는지
if(count[c-'a'][1] == 1)
{
int j = count[c-'a'][0];
answer.push_back(i-j);
count[c-'a'][0] = i; // 뒤에서 또 같은 문자 나올 수도 있으니 인덱스정보 업데이트
i++;
}
else
{
count[c-'a'][0] = i;
count[c-'a'][1] = 1;
i++;
answer.push_back(-1);
}
}
return answer;
}
하지만, 다른 사람 풀이를 보니 map으로 더 간단히 풀 수 있었다.
#include <string>
#include <vector>
#include <map>
using namespace std;
vector<int> solution(string s)
{
map<char, int> mp;
vector<int> answer;
for (int i = 0; i < s.size(); ++i)
{
if (mp.find(s[i]) != mp.end()) answer.push_back(i - mp[s[i]]);
else answer.push_back(-1);
mp[s[i]] = i;
}
return answer;
}