[LeetCode] 151. Reverse Words in a String
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
".
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
For C programmers: Try to solve it in-place in O(1) space.
Clarification:
Time complexity: O(n).
- 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.
Thought process:
Reverse the string, split the string by space, reverse each word, and put the words together. Use StringBuilder instead of string "+" operator to improve time complexity. Also note that if there are multiple spaces between words, string.split() will return an empty string. Remember to check for that when concatenating the words.
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public class Solution { public String reverseWords(String s) { String sReversed = new StringBuilder(s).reverse().toString(); String[] reversedWords = sReversed.split(" "); StringBuilder sb = new StringBuilder(); for (String word : reversedWords) { if (word.length() > 0) { sb.append(new StringBuilder(word.trim()).reverse()); sb.append(' '); } } return sb.toString().trim(); } } |
Time complexity: O(n).
Comments
Post a Comment