-
[LeetCode] 557. Reverse Words in a String III c++Coding Test/LeetCode 2022. 12. 26. 17:59728x90
- 문제
Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Input: s = "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc"
문장에 있는 각 단어의 순서를 반대로 바꾸는 문제입니다.
- 문제 해결
class Solution { private: void parseString(string& str, vector<string>& vec, const string& delimiter){ int pos = 0; while( (pos = str.find(delimiter)) != string::npos ){ string tmp = str.substr(0, pos); vec.push_back(tmp); str.erase(0, pos + delimiter.length()); } vec.push_back(str); } public: string reverseWords(string s) { vector<string> vec; string delimiter(" "); parseString(s, vec, delimiter); string result(""); for(const auto& it : vec){ string tmp = it; int i = 0, j = it.size() -1; while( i < j){ swap(tmp[i++], tmp[j--]); } result += tmp + " "; } result.erase(result.size()-1); return result; } };
다른 풀이
class Solution { public: string reverseWords(string s) { int i = 0; for(int j = 0; j < s.size(); ++j){ if( s[j] == ' '){ reverse(s.begin() + i, s.begin() + j); i = j + 1; } } reverse(s.begin() + i, s.end()); return s; } };
728x90'Coding Test > LeetCode' 카테고리의 다른 글
[LeetCode] 19. Remove Nth Node From End of List c++ (0) 2022.12.27 [LeetCode] 876. Middle of the Linked List c++ (0) 2022.12.26 [LeetCode] 344. Reverse String c++ (0) 2022.12.26 [LeetCode] 167. Two Sum II - Input Array Is Sorted c++ (0) 2022.12.26 [LeetCode] 283. Move Zeroes c++ (0) 2022.12.24