将每个元素存储为单个字符的句子单词逆序的 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, ]
广告