Questions
space 마다 단어를 반대로 만들어서 리턴해주는 문제이다. space의 개수 만큼 reverse words에도 추가해줘야 한다.
Examples
"This is an example!" ==> "sihT si na !elpmaxe" "double spaces" ==> "elbuod secaps"
Solutions
using namespace std; int checkEmptyCount(string str, int startIndex) { int count = 0; for(int i=startIndex; i<(int)str.size(); i++) { if(str[i] == ' ') count++; else break; } return count; } string reverse_words(string str) { string reverse; char * start = &str[0]; char * end = &str[0]; if (str.empty()) { return reverse; } for(int i=0; i<(int)str.size(); i++) { if(str[i] == ' ') { end--; char * temp = &str[i]; while(start != end) { reverse += *end; end--; } reverse += *start; int empty_count = checkEmptyCount(str, i); // cout << "empty_count = " << empty_count << endl; for(int j=0; j<empty_count; j++) { reverse += ' '; temp++; i++; } // cout << "reverse = " << reverse << endl; // cout << "i = " << i << " size = " << str.size() << endl; // cout << "temp = " << temp << " start = " << *start << " end = " << *end << endl; if (i == str.size()) return reverse; start = temp; end = temp; } end++; } end--; //cout << "start = " << *start << " end = " << *end <<endl; while(start != end) { reverse += *end; end--; } reverse += *start; //cout << "reverse2 = " << reverse << endl; return reverse; }
내 솔루션은 two pointer 전략으로 2개의 포인터(start, end)를 가지고 있고
문자의 size만큼 for문을 돌면서 space가 나오면 end에서 부터 start까지 내려가면서 reverse문자열에 넣어주는 방식이다.
이렇게 코딩을 하니 디버깅해야 될 것들이 많았다. 예외 케이스들이 많아서...
뭔가 깔끔한 코드는 아닌 것 같다.
그래서 best 답안을 가지고 왔다.
std::string reverse_words(std::string str) { std::string out; std::string cword; for (char c : str) { if (c == ' ') { out += cword; out += c; cword = ""; continue; } cword = c + cword; } out += cword; return out; }
여기도 for문으로 str을 전부 도는건 동일하고 c가 space이면 out에 cword를 저장하고 c를 저장하는데 cword는 space에 오면 매번 초기화 된다.
cword = c + cword; 이므로 str이 거꾸로 저장이되는 것이다.
예를 들어 아래 str 이 아래 문장이면
This is an example!
sihT가 cword에 저장이 되고 이제 c가 This와 is 사이에 오면 out에 sihT를 저장하고 out에 c (여기서 space)를 저장한다.
그리고 cword를 초기화 해주는데 여기서 신박했던게 space가 여러번 오면 어떻게 처리하지? 고민했는데
c가 space이면 out에 c를 추가해주면 되는거였다. cword는 공백일거라 문제가 없을거고...
내가 짠 방식에서는 이러한 방식이 불가능했어서 space가 오면 space가 연속으로 몇개오는지 구해서 그만큼 c의 위치를 옮겨주는 방식이었는데 더 복잡했던 것 같다.
이번 문제는 여기까지!
'알고리즘 > Codewars' 카테고리의 다른 글
Codewars - [5 kyu] Simple assembler interpreter (0) | 2022.04.29 |
---|---|
Codewars - [6 kyu] Sum consecutives (0) | 2022.01.17 |
댓글