您的位置:首页 > 编程语言 > Go语言

LeetCode -- ReverseWordsinaString

2014-07-15 20:24 267 查看
Given an input string, reverse the string word by word.

For example,

Given s = "
the sky is blue
",

return "
blue is sky the
".

有两种特殊情况需要考虑:

1、全是空格,如输入为“      ”,输出就应该为“”;

2、单词与单词之间的空格不止一个,如“1       2    ”,应该产生的结果为“1 2”,但是用java的String.split得出的数组元素里面是会有空格的存在,所以应该排除;

3、字符串一开始就有空格,如“      1   ”,用split产生的数组第一个为“”,所以也应该考虑。

public class Solution {
public String reverseWords(String s){

String []temp = s.split(" ");
int len = temp.length;

if(len == 0)return "";

int neworder = 0;
for(int i = 0 ; i < len; ++i){
if(temp[i].equals("")||temp[i].equals(" "))
continue;
temp[neworder++] = temp[i];
}

String result = "";
for(int i = neworder-1; i > 0; --i){
result = result + temp[i] + " ";
}
result = result + temp[0];
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  algorithm leetcode