C++)
#include <string>
#include <vector>
#include <algorithm>
#include <array>
using namespace std;
vector<int> solution(string s) {
array<int, 26> alp;
std::fill(alp.begin(), alp.end(), -1);
vector<int> answer;
for(int idx = 0; idx < s.length(); idx++) {
if(alp.at(s[idx]-'a') == -1) { // 지금까지 해당 알파벳이 안 나왔었다면
answer.push_back(-1); // -1을 넣고
alp.at(s[idx]-'a') = idx; // 위치 갱신
} else { // 나왔었다면
answer.push_back(idx-alp.at(s[idx]-'a')); // 가장 가까운 위치를 넣고
alp.at(s[idx]-'a') = idx; // 위치 새롭게 갱신
}
}
return answer;
}
Python)
def solution(s):
alp = [-1 for _ in range(26)]
ans = []
for idx, ch in enumerate(s):
pos = ord(ch)-ord('a')
ans.append(-1 if alp[pos] == -1 else idx - alp[pos])
alp[pos] = idx
return ans
'프로그래머스 > Level1' 카테고리의 다른 글
| [Level1] 명예의 전당 (1) (C++/Python) (0) | 2023.02.14 |
|---|---|
| [Level1] 실패율 (C++) (0) | 2023.02.10 |
| [Level 1] 소수 만들기 (C++/Python) (0) | 2023.02.08 |
| [Level 1] 모의고사 (C++/Python) (0) | 2023.02.07 |
| [Level1] 콜라 문제 (C++/Python) (0) | 2023.02.07 |