i
인 단위가 되는 문자열을 temp
에 저장하고 (temp=s.substr(0,i))
바로 뒤에 있는 문자열이 temp와 같으면 cnt
를 증가시키고, 다르다면 string convert
(새로 변환한 문자를 저장하는 string)에 저장한다.convert
에 저장한 후 현재 위치(j)
부터 i길이인 문자열을 다시 단위가 되는 문자열로 바꾸기 위해 temp에 저장 (temp=s.substr(j,i);)
i
가 바뀔 때마다 convert
의 길이를 비교하여 최소가 되는 길이를 반환한다.#include <string> #include <vector> using namespace std; int solution(string s) { int answer = s.size(); for (int i=1; i<=s.size(); i++) { string convert, temp; int cnt=1; temp=s.substr(0,i); for (int j=i; j<s.size(); j+=i) { if (temp==s.substr(j,i)) cnt++; else { if (cnt>1) convert+=to_string(cnt); convert+=temp; temp=s.substr(j,i); cnt=1; } } if (cnt>1) convert+=to_string(cnt); convert+=temp; if (answer>convert.size()) answer=convert.size(); } return answer; }