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
".
public class Solution {
public String reverseWords(String s) {
String tks[] = s.split("\\s+");
StringBuilder sb = new StringBuilder();
for(int k=tks.length-1;k>=0;k--) {
sb.append(tks[k]).append(" ");
}
return sb.toString().trim();
}
}
==============public class Solution {
public String reverseWords(String s) {
if (s == null || s.length() < 1) {
return s;
}
char[] cs = s.toCharArray();
swap(cs, 0, cs.length - 1);
int i = 0;
while (i < cs.length) {
while (i < cs.length && Character.isWhitespace(cs[i])) i++;
int start = i;
while (i < cs.length && !Character.isWhitespace(cs[i])) i++;
int end = i - 1;
swap(cs, start, end);
}
StringBuilder sb = new StringBuilder();
for (i = 0; i < cs.length; i++) {
if (i != 0 && cs[i] == ' ' && cs[i] == cs[i - 1]) {
continue;
}
sb.append(cs[i]);
}
return sb.toString().trim();
}
private void swap(char[] cs, int s, int e) {
while (s < e) {
char tmp = cs[s];
cs[s] = cs[e];
cs[e] = tmp;
s++;
e--;
}
}
}
没有评论:
发表评论