(Leetcode)Reverse Words in a String
2014-08-18 15:04
411 查看
Reverse Words in a String
题目如下:
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.新创建一个字符串,从后遍历字符串数组,将每个遍历到的字符串拼接到新创建的字符串后面,并用“ ”隔开
题目如下:
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.新创建一个字符串,从后遍历字符串数组,将每个遍历到的字符串拼接到新创建的字符串后面,并用“ ”隔开
public class Solution { public String reverseWords(String s) { if(s==null) return s; if(s.trim().isEmpty()){ s=""; return s; } String[] words=s.trim().split(" "); String str=""; for(int i=words.length-1;i>=0;i--){ if(words[i].equals("")) continue; //判断是否到达第一个字符串数组,防止多 //加入空格 if(i!=0) str+=words[i].trim()+" "; else str+=words[i].trim(); } return str; } }
相关文章推荐
- 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