AC代码例如以下: classSolution{public:voidreverseWords(string&s){if(s.empty())return;intcount=0;intindex=0,indexTemp=0,begin=0,end=s.length()-1;while(s[begin]==' '&&begin<s.length()-1)begin++;while(s[end]==' '&&end>0)end--;if(end==0&&s[end]==' '){s="";return;}elsei...
A sequence of non-space characters constitutes a word. 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. ...
For C programmers: Try to solve it in-place in O(1) space. 对于Java实现,直接分割字符串然后逆序即可。 代码如下: public class Solution { public String reverseWords(String s) { if(s==null || s.length()<=0) return s; s=s.trim(); String []res=s.split("\\s+"); if(res.length<...
publicstaticStringreverseWords(String s){ s = s.trim(); s=remove(s);char[] c = s.toCharArray();intpre=0;for(inti=0; i < c.length; i++) {if(c[i] ==' ') { reverse(c, pre, i -1); pre = i +1; }elseif(i == c.length -1) { reverse(c, pre, i); } }returnnew...
题目:Given an input string, reverse the string word by word.For example,Given s = "the sk...
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string. 将原来字符串中各个单词单独反转,然后拼在一起,再一起反转。 注意两边和中间的空格,原字符串中间可能有好几个空格,但是反转后只有一个,两边的空格都要去掉。
publicStringreverseWords(Strings){if(s==null)returnnull;char[]a=s.toCharArray();intn=a.length;// step 1. reverse the whole stringreverse(a,0,n-1);// step 2. reverse each wordreverseWords(a,n);// step 3. clean up spacesreturncleanSpaces(a,n);}voidreverseWords(char[]a,intn){int...
public static string ReverseWordsInString(string str) { string reverse = ReverseString(str); string temp = ""; foreach (string s in reverse.Split(' ')) { temp += ReverseString(s) + ' '; } return temp; } private static string ReverseString(string str) ...
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. fromcollectionsimportdequeclassSolution(object):defreverseWords(self,s):""":type s: str:rtype: str"""ifs==''...
public static string ReverseWordsInString(string str) { string reverse = ReverseString(str); string temp = ""; foreach (string s in reverse.Split(' ')) { temp += ReverseString(s) + ' '; } return temp; } private static string ReverseString(string str) { char[] chars = str.ToCharA...