151. Reverse Words in a String

来源:互联网 发布:懒人js特效 编辑:程序博客网 时间:2024/06/05 03:46

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.

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.

使用正则 \\s+ 分割单词,除了前导的空格,其他的任意长度的空格段都被删除。前导的空格分割后在数组里是一个空串,特殊处理一下即可。
public class Solution {    public static String reverseWords(String s){if(s.isEmpty())return "";String[] strs=s.split("\\s+");StringBuilder sb=new StringBuilder();int len=strs.length;if(len>0){for(int i=0,j=len-1;i<len;i++,j--){if(strs[j].length()<1)continue;sb.append(strs[j]);sb.append(' ');}sb.deleteCharAt(sb.length()-1);}return sb.toString();}}


0 0
原创粉丝点击