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
".
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.
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
package leetcode; | |
import java.util.ArrayList; | |
/** | |
* Solution: String split and construct. | |
* | |
* Take care: | |
* !"".equals(words[i]) but not " ". after split,there's "" | |
* | |
* Test Case: | |
* " a bb" --> "bb a" | |
* " " --> "" this situation, sb.length() == 0 | |
* @author jeffwan | |
* @date Apr 1, 2014 | |
*/ | |
public class ReverseWords { | |
public String reverseWords(String s) { | |
if (s == null || s.length() == 0) { | |
return ""; | |
} | |
String[] words = s.split(" "); //Get every single word. | |
StringBuilder sb = new StringBuilder(); | |
for (int i = words.length - 1; i >= 0; i--) { | |
if (!"".equals(words[i])) { | |
sb.append(words[i] + " "); | |
} | |
} | |
return sb.length() == 0 ? "" : sb.toString().substring(0, sb.length() - 1); | |
} | |
// My way split word is not clear efficiency enough. | |
// I go pass every char to see if it's " ".Should use string.split(" ") direcly. | |
public String reverseWords2(String s) { | |
if (s == null || s.length() == 0) { | |
return ""; | |
} | |
ArrayList<String> list = new ArrayList<String>(); | |
s = s.trim(); | |
int wordBegin = 0; | |
for (int i = 0; i < s.length(); i++) { | |
if (' ' == s.charAt(i)) { | |
list.add(0, s.substring(wordBegin, i)); | |
while (' ' == s.charAt(i)) { | |
i++; | |
} | |
wordBegin = i; | |
} | |
} | |
list.add(0, s.substring(wordBegin, s.length())); | |
StringBuilder sb = new StringBuilder(); | |
for (String word : list) { | |
sb.append(word + " "); | |
} | |
return sb.toString().substring(0, sb.length() - 1); | |
} | |
} |
No comments:
Post a Comment