Problem
Given an input string, reverse the string word by word.
For example,
Given s = "
return "
Given s = "
the sky is blue
",return "
blue is sky the
".Analysis
- 首先split string by space
- 然后 append word in reverse order
- 注意 如果当前非空,在append下一个word之前,需要append空格
Code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 2015/12/25 | |
// Highlight: string split | |
public class Solution { | |
public String reverseWords(String s) { | |
//split string | |
String[] words = s.split(" "); | |
StringBuilder sb = new StringBuilder(); | |
//append in reverse order | |
for(int i=words.length-1; i>=0; i--){ | |
if(words[i].equals("")) continue; | |
if(sb.length()!=0) sb.append(" "); | |
sb.append(words[i]); | |
} | |
return sb.toString(); | |
} | |
} |
Reference
No comments:
Post a Comment