Given an input string s, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space.
Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
Input: s = "the sky is blue"
Output: "blue is sky the"
Input: s = " hello world "
Output: "world hello"
Explanation: Your reversed string should not contain leading or trailing spaces.
Input: s = "a good example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
'.시간 복잡도:
문자열을 한번 순회하며 단어를 분리 → O(N)
단어 리스트를 뒤집기 → O(N)
단어를 다시 결합하기 → O(N)
따라서 전체 시간 복잡도는 O(N).
공간 복잡도:
첫 번째 방법에서는 단어 리스트를 저장하므로 O(N) 추가 공간이 필요.
두 번째 방법(in-place)은 O(1) 추가 공간을 유지.
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
using namespace std;
string reverseWords(string s) {
stringstream ss(s);
string word;
vector<string> words;
// 공백을 기준으로 단어 분리
while (ss >> word) {
words.push_back(word);
}
// 단어 순서 뒤집기
reverse(words.begin(), words.end());
// 단어들을 다시 공백으로 결합
string result;
for (int i = 0; i < words.size(); i++) {
if (i > 0) result += " ";
result += words[i];
}
return result;
}
//
int main() {
string s = " hello world ";
cout << "Output: \"" << reverseWords(s) << "\"" << endl; // Expected: "world hello"
return 0;
}
#include <iostream>
#include <algorithm>
using namespace std;
// in-place
void reverseString(string &s, int left, int right) {
while (left < right) {
swap(s[left++], s[right--]);
}
}
string reverseWordsInPlace(string s) {
int n = s.size();
// 1. 전체 문자열을 뒤집기
reverseString(s, 0, n - 1);
// 2. 각 단어를 개별적으로 뒤집기
int start = 0, end = 0, writeIndex = 0;
while (end < n) {
// 공백 건너뛰기
while (end < n && s[end] == ' ') end++;
if (end == n) break;
// 단어의 시작점
start = end;
// 단어의 끝까지 이동
while (end < n && s[end] != ' ') end++;
// 단어를 뒤집기
reverseString(s, start, end - 1);
// 단어를 앞으로 당겨서 정리
if (writeIndex != 0) s[writeIndex++] = ' ';
while (start < end) s[writeIndex++] = s[start++];
}
// 3. 문자열의 크기를 조정하여 불필요한 공백 제거
s.resize(writeIndex);
return s;
}
//
int main() {
string s = " hello world ";
cout << "Output: \"" << reverseWordsInPlace(s) << "\"" << endl; // Expected: "world hello"
return 0;
}