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

กลับลำดับคำในสตริง II ใน C++


สมมติว่าเรามีสตริงนำเข้าหนึ่งสตริง เราต้องกลับลำดับคำในสตริงทีละคำ

ตัวอย่าง: อินพุต ["t","h","e"," ","m","a","n"," ","i","s"," ","n","i","c","e"] ผลลัพธ์: ["n","i","c","e"," ","i","s"," ","m","a","n"," ","t","h","e"]

วิธีแก้ปัญหา

  1. กลับอาร์เรย์ทั้งหมด
  2. เดินผ่านอาร์เรย์ กลับแต่ละคำทีละคำเมื่อเจอช่องว่าง
  3. กลับคำสุดท้าย

ตัวอย่างโค้ด C++

#include <bits/stdc++.h> 
using namespace std; 

void print_vector(vector<char> 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); 
    } 
}; 

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