在 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"]

要解決這個問題,我們將遵循以下步驟 -

  • 反轉陣列 s

  • j := 0

  • n := s 的大小

  • 對初始化 i := 0 時,當 i < n 時,更新(將 i 遞增 1),執行 -

    • 如果 s[i] 與 ' ' 相同,則 -

      • 反轉從索引 j 到 i 的陣列 s

      • j := i + 1

  • 反轉從索引 j 到 n 的陣列 s

示例 

讓我們看以下實施,以獲得更好的理解 -

 現場演示

#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, ]

更新於: 2020-11-18

777 次瀏覽

開啟您的職業生涯

透過完成該課程獲得認證

立即開始
廣告
© . All rights reserved.