您的位置:首页 > 其它

Reverse Words in a String III(leetcode)

2017-10-26 20:16 274 查看

Reverse Words in a String III

Reverse Words in a String III
题目

解析

解决

题目

leetcode题目

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving white space and initial word order.

Example 1:

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"


Note: In the string, each word is separated by single space and there will not be any extra space in the string.

解析

题目需要我们做的事情是将给定字符串中的单词前后颠倒,而单词本身在字符串的位置以及字符串中的空格位置不变。

Example 1
中,给定的字符串为
Let's take LeetCode contest
,则我们以空格为分界,将字符串分成
Let's
take
LeetCode
contest
4个子字符串,再分别对其前后颠倒,以实现题目要求。

解决

class Solution {
public:
string reverseWords(string s) {
string result, temp;
int subpos = 0;
int sublen = 0;
int len = s.length();
for (int i = 0; i < len; i++) {
if (s[i] == ' ') {
result += reverse(s.substr(subpos, sublen)) + ' ';
subpos = i + 1;
sublen = 0;
} else if (i == len - 1){
result += reverse(s.substr(subpos, sublen + 1));
} else {
sublen++;
}
}
return result;
}

string reverse(string s) { // 对子字符串进行颠倒
string result;
int len = s.length();
for (int i = len - 1; i > -1; i--) {
result += s[i];
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: