각 요소가 단일 문자로 저장되는 하나의 입력 문자열 문장이 있다고 가정하고 단어별로 문자열을 반대로 해야 합니다.
따라서 입력이 ["t","h","e"," ","m","a","n"," ","i","s"," ","와 같은 경우 n","l","c","e"]인 경우 출력은 ["n","l","c","e"," ","i","s"," ","m","a","n"," ","t","h","e"]
이 문제를 해결하기 위해 다음 단계를 따릅니다. −
-
배열 반전
-
j :=0
-
n :=s
의 크기 -
initialize i :=0의 경우, i
-
s[i]가 ' '와 같으면 -
-
배열 s를 인덱스 j에서 i로 반전
-
j :=i + 1
-
-
-
배열 s를 인덱스 j에서 n으로 반전
이해를 돕기 위해 다음 구현을 살펴보겠습니다. −
예
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << v[i] << ", ";
}
cout << "]"<<endl;
}
class Solution {
public:
void reverseWords(vector<char>& s) {
reverse(s.begin(), s.end());
int j = 0;
int n = s.size();
for(int i = 0; i < n; i++){
if(s[i] == ' '){
reverse(s.begin() + j, s.begin() + i);
j = i + 1;
}
}
reverse(s.begin() + j, s.begin() + n);
}
};
main(){
Solution ob;
vector<char> v = {'t','h','e',' ','m','a','n',' ','i','s','
','n','i','c','e'};
ob.reverseWords(v);
print_vector(v);
} 입력
{'t','h','e',' ','m','a','n',' ','i','s',' ','n','i','c','e'} 출력
[n, i, c, e, , i, s, , m, a, n, , t, h, e, ]