Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรมย้อนกลับคำในประโยคที่เก็บไว้เป็นอาร์เรย์อักขระใน 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

  • เจ :=0

  • n :=ขนาดของ s

  • สำหรับการเริ่มต้น i :=0 เมื่อ i

    • ถ้า s[i] เหมือนกับ ' ' แล้ว −

      • ย้อนกลับอาร์เรย์ s จากดัชนี 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, ]