您的位置:首页 > 其它

[Leetcode] Reverse Words in a String

2014-04-23 14:44 357 查看
Reverse Words in a String

Given an input string, reverse the string word by word. 

Given s = "
the sky is blue
",

        return "
blue is sky the
".

Clarification:

1 What constitutes a word? 
A sequence of non-space characters constitutes a word.
2 Could the input string contain leading or trailing spaces? 
Yes. However, your reversed string should not contain leading or trailing spaces.
3  How about multiple spaces between two words?   
Reduce them to a single space in the reversed string.
Solution1:一次扫描翻转。 设置两个动态游标,last表示 未被扫描的结尾处, i表示word之前空格处

public class Solution {
public String reverseWords(String s) {
if (s == null)
return "";
s = s.trim();
if (s == "")
return "";
StringBuffer sb = new StringBuffer();
int i = s.length() - 1;
int last = i;
while (i >= 0) {
while (i >= 0 && s.charAt(i) != ' ') {
i--;
}
String temp = s.substring(i + 1, last + 1);
sb.append(temp);
sb.append(" ");
while (i >= 0 && s.charAt(i) == ' ') {
i--;
}
last = i;
}
while (sb.length() > 1 && sb.charAt(sb.length() - 1) == ' ')
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
}


Solution2:先整体翻转,然后再每个word翻转。 利用一个Stack,注意最后的结尾处

static String reverseWords(String str) {
System.out.println(str);
char[] strCh = str.toCharArray();
int len = strCh.length;
char[] tmp = new char[len];

for (int i = 0; i < len; i++) {
tmp[len - i - 1] = strCh[i];
}

Stack stack = new Stack();
int wordLen = 0;

for (int i = 0; i < len; i++) {
if (tmp[i] == ' ' || tmp[i] == ',' || tmp[i] == '?') {
for (int j = 0; j < wordLen; j++) {
tmp[i - wordLen + j] = (char) stack.pop();
}
wordLen = 0;
stack.clear();
} else if (i == len - 1) {
stack.push(tmp[i]);
wordLen++;
for (int j = 0; j < wordLen; j++) {
tmp[i - wordLen + j + 1] = (char) stack.pop();
}
} else {
stack.push(tmp[i]);
wordLen++;
}
}

return new String(tmp);
}







                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: