LeetCode -- ReverseWordsinaString
2014-07-15 20:24
267 查看
Given an input string, reverse the string word by word.
For example,
Given s = "
return "
有两种特殊情况需要考虑:
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;
}
};
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;
}
};
相关文章推荐
- Leetcode 第151题 最新题解 Reverse Words in a String
- leetcode JAVA Reverse Words in a String 难度系数2-3?最新题151
- LeetCode(151)Reverse Words in a String
- Leetcode: Reverse Words in a String
- LeetCode Reverse Words in a String
- 【LeetCode with Python】 Reverse Words in a String
- [LeetCode]Reverse Words in a String
- leetcode Reverse Words in a String
- [leetcode]Reverse Words in a String
- Leetcode_Reverse-Words-in-a-String
- LeetCode | Reverse Words in a String
- Reverse Words in a String (LeetCode)
- [Leetcode Solution] Reverse Words in a String
- LeetCode151:Reverse Words in a String
- 【LeetCode】Reverse Words in a String
- [leetCode]Reverse Words in a String
- leetcode - Reverse Words in a String
- [LeetCode] Reverse Words in a String
- 【LeetCode】Reverse Words in a String
- 【LeetCode】Reverse Words in a String