leetcode面試題目-反轉字串中的單詞 III
阿新 • • 發佈:2021-02-02
技術標籤:leetcode解題總結面試leetcode演算法
leetcode面試題目-反轉字串中的單詞 III
題目在這 https://leetcode-cn.com/
給定一個字串,你需要反轉字串中每個單詞的字元順序,同時仍保留空格和單詞的初始順序。
示例:
輸入:“Let’s take LeetCode contest”
輸出:“s’teL ekat edoCteeL tsetnoc”
提示:
在字串中,每個單詞由單個空格分隔,並且字串中不會有任何額外的空
程式碼:
#include<iostream>
#include<string.h>
using namespace std;
string reverseWords(string s) {
string re="";
string re1="";
for(int i=0;i<s.length();i++){
if(s[i] != ' '){
re=s[i]+re;
}
if(s[i] == ' ' || i == s.length()-1){
re1 += re;
re="";
if(i != s.length()-1) re1+=" ";
}
}
return re1;
}
int main()
{
string s="Let's take LeetCode contest";
cout << reverseWords(s);
}
輸出結果: