在 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, ]
广告