將每個元素儲存為單個字元的句子單詞逆序的 C++ 程式


假設我們有一個輸入字串句子,其中每個元素都儲存為單個字元,我們必須按單詞逆序字串。

因此,如果輸入類似於 ["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-10-21

1K+ 瀏覽量

開啟你的 職業之旅

完成課程獲得認證

立即開始
廣告