leetcode面试题目-反转字符串中的单词 III

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);
}

输出结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/bubbleSweet/article/details/112951497