Leetcode[151] Reverse Words in a String
12 Nov 2015###Task1 Given an input string, reverse the string word by word.
For example, Given s = “the sky is blue”, return “blue is sky the”.
###Python ####Three steps
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
if not s or len(s) == 0:
return s
li = s.split()
rev = []
for ori in li:
rev.append(ori[::-1])
return ' '.join(rev)[::-1]
####Python
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
if not s or len(s) == 0:
return s
return ' '.join(s.split()[::-1])
####By Char
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
res = ''
word = ''
for ch in s:
if ch != ' ':
word += ch
elif len(word) > 0:
if len(res) != 0:
res = ' ' + res
res = word + res
word = ''
if len(word) > 0:
if len(res) != 0:
res = ' ' + res
res = word + res
return res
###Java
public class Solution {
public String reverseWords(String s) {
if (s == null || s.length() == 0) {
return "";
}
s = s.trim();
StringBuilder sb = new StringBuilder();
StringBuilder res = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') {
if (sb.length() == 0) {
continue;
} else {
res.append(sb.reverse());
if (i != s.length() - 1) {
res.append(" ");
}
sb.delete(0, sb.length());
}
} else {
sb.append(s.charAt(i));
}
}
res.append(sb.reverse());
return res.reverse().toString();
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.reverseWords(" 1 "));
}
}
####By split
public class Solution {
public String reverseWords(String s) {
if (s == null || s.length() == 0) {
return "";
}
String[] arr = s.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = arr.length - 1; i >= 0; i--) {
if (!arr[i].equals("")) {
sb.append(arr[i]).append(" ");
}
}
//remember to remove the last " "
return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.reverseWords(" 1 "));
}
}
###Points
- Three steps reversing
- This can be done in a char-by-char order.
- O(n)