53 · Reverse Words in a String - LintCode
# Description
Given an input string, reverse the string word by word.
- What constitutes a word?
A sequence of non-space characters constitutes a word and some words have punctuation at the end. - 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.
# Example
Example 1:
Input:
s = "the sky is blue"
Output:
"blue is sky the"
Explanation:
return a reverse the string word by word.
# Solution
- use String Builder
- check if the String array[index] equals to ""
- append a space " " when the result.length > 0, so the first one will never add a " ";
- remember StringBuilder has to use toString()
public class Solution { | |
/** | |
* @param s: A string | |
* @return: A string | |
*/ | |
public String reverseWords(String s) { | |
StringBuilder res = new StringBuilder(); | |
String[] sArray = s.split(" "); | |
for (int i = sArray.length - 1; i >= 0; i--){ | |
if (!sArray[i].equals("")){ | |
if (res.length() > 0) { | |
res.append(" "); | |
} | |
res.append(sArray[i]); | |
} | |
} | |
return res.toString(); | |
} | |
} |