Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++의 문자열 II에서 단어 반전

<시간/>

입력 문자열이 하나 있다고 가정하고 문자열을 단어 단위로 바꿔야 합니다.

따라서 입력이 ["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, ]