本文主要是介绍LeetCode 题解(262) : Reverse Words in a String II,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces and the words are always separated by a single space.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
Could you do it in-place without allocating extra space?
Related problem: Rotate Array
题解:先反转整个string,在反转每个单词。
C++版:
class Solution {
public:void reverseWords(string &s) {reverse(s.begin(), s.end());int i = 0;while(i < s.length()) {int j = i;while(j < s.length() && s[j] != ' ')j++;for(int k = i; k < i + (j - i) / 2; k++) {int t = s[k];s[k] = s[i + j - 1 - k];s[i + j - 1 - k] = t;}i = j + 1;}}
};
Python版:
class Solution(object):def reverseWords(self, s):""":type s: a list of 1 length strings (List[str]):rtype: nothing"""s.reverse()i = 0while i < len(s):j = iwhile j < len(s) and s[j] != " ":j += 1for k in range(i, i + (j - i) / 2 ):t = s[k]s[k] = s[i + j - 1 - k]s[i + j - 1 - k] = ti = j + 1
这篇关于LeetCode 题解(262) : Reverse Words in a String II的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!