Could the input string contain leading or trailing spaces? Yes. However, your reversed string should not contain leading or trailing spaces. How about multiple spaces between two words? Reduce them to a single space in the reversed string. SOLUTION 1: 1. 先处理原字符串: 使用strim把前后的空格...
思路和做法1一样,只是为了消空格方便,用string流。 Time complexity: O(n) Space complexity: O(n) classSolution{public:voidreverseWords(string &s){reverse(s.begin(), s.end());stringstreamss(s); string str, ret;while(ss >> str) {reverse(str.begin(), str.end());for(charc : str) { ...
# @param s, a string # @return a string def reverseWords(self, s): if len(s) == 0: return '' words = s.split(' ') i = 0 while i < len(words): if words[i] == '': del words[i] else: i = i + 1 if len(words) == 0: return '' words.reverse() result = '' ...
1. Leetcode_easy_557. Reverse Words in a String III; 2. Grandyang; 完
Can you solve this real interview question? Reverse Words in a String III - Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. Example 1: Input: s = "Let's take
输入:s = "a good example" 输出:"example good a" 解释:如果两个单词间有多余的空格,反转后的字符串需要将单词间的空格减少到仅有一个。 提示: 1 <= s.length <= 104 s 包含英文大小写字母、数字和空格 ' ' s 中至少存在一个 单词 进阶:如果字符串在你使用的编程语言中是一种可变数据类型,请尝试...
1. Description Reverse Words in a String III 2. Solution class Solution{public:stringreverseWords(string s){intstart=0;for(inti=0;i<s.length();i++){if(s[i]==' '){reverse(s,start,i-1);start=i+1;}}reverse(s,start,s.length()-1);returns;}private:voidreverse(string&s,intstart,...
My code: publicclassSolution{publicvoid reverseWords(char[]s){if(s==null||s.length==0)return;intbegin=s.length-1;intend=s.length-1;while(end>=0){char curr=s[end];if(begin==end){if(curr==' '){end--;begin--;}else{end--;}}else{if(curr==' '){reverse(s,end+1,begin);end...
class Solution { public: void reverseWords(string &s) { s = removeDuplicateSpace(s); int begin = 0; int end = 0; while(end < s.size()){ if(s[end] == ' '){ swapString(s, begin, end - 1); begin = end+1; end = begin; } else{ end++; } } swapSt...
1classSolution:2#@param s, a string3#@return a string4defreverseWords(self, s):5ss = s.split("")6ss = filter(lambdax:x!="",ss)7l =len(ss)8foriinrange(l/2):9ss[i],ss[l-1-i] = ss[l-1-i],ss[i]10s = ("").join(ss)11returns ...