leetcode_Reverse Words in a String

来源:互联网 发布:php网站如何搭建 编辑:程序博客网 时间:2024/05/07 15:34

描述:

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

click to show clarification.

Clarification:

  • What constitutes a word?
    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.

思路:

1.trim()+去除串内多余的空格

2.将串内每个单词反转

3.将整个句子反转

代码:

public String reverseWords(String s) {s=s.trim();if(!s.equals("")){char arr[]=s.toCharArray();int index=1;for(int i=1;i<arr.length;i++){if(arr[i-1]==arr[i]&&arr[i]==' ')continue;elsearr[index++]=arr[i];}s=new String(arr,0,index);}else {return "";}StringBuilder sBuilder=new StringBuilder(s);char ch;int i=0,j=s.length()-1;int start=0,end=0;for(i=0;i<sBuilder.length();i++){start=i;while(sBuilder.charAt(i)!=' '&&i!=j)i++;end=i;if(end!=j)end--;while(start<end){ch=sBuilder.charAt(start);sBuilder.setCharAt(start, sBuilder.charAt(end));sBuilder.setCharAt(end, ch);start++;end--;}}sBuilder.reverse();        return sBuilder.toString();    }



0 0