您的位置:首页 > 其它

【LintCode】Reverse Words in a String 翻转字符串

2015-07-14 21:27 519 查看
中文描述:

给定一个字符串,逐个翻转字符串中的每个单词。

我曾在百度的实习面试中遇到过这道题。

样例

给出s = “the sky is blue”,返回”blue is sky the”

说明

单词的构成:无空格字母构成一个单词。

输入字符串是否包括前导或者尾随空格?可以包括,但是反转后的字符不能包括。

如何处理两个单词间的多个空格?在反转字符串中间空格减少到只含一个。

English Version:

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

For example,

Given s = “the sky is blue”,

return “blue is sky the”.

Clarification

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.

基本思路:

1)第一趟遍历

将每个单词翻转,且去掉连续空格中多余的空格(两端空格早已去掉)。

2)第二趟遍历

将整个字符串完全翻转。

public class Solution {
/**
* @param s : A string
* @return : A string
*/
public String reverseWords(String s) {
StringBuilder sb = new StringBuilder(s.trim());
//第一趟遍历
for(int i = 0; i < sb.length();) {
if(i+1 < sb.length() && sb.charAt(i) == ' ' && sb.charAt(i) == sb.charAt(i + 1)){//单词间连续空格,将多个空格减至一个
sb.deleteCharAt(i+1);
i++;
continue;
}else if(sb.charAt(i) != ' ') {//单词,将单词翻转
int j = i;
while(j+1 < sb.length() && sb.charAt(j + 1) != ' ') {//找到该单词最后一个字母
j++;
}
for(int k = 0; k < (j - i + 1)/2; k++) {//将单词翻转
char c = sb.charAt(k + i);
sb.setCharAt(k + i, sb.charAt(j - k));
sb.setCharAt(j - k, c);
}
i = j+1;
}else {//一个空格
i++;
}
}
//第二趟遍历
for(int i = 0; i < sb.length()/2; i++) {//从两端开始,前后互换
char c = sb.charAt(i);
sb.setCharAt(i, sb.charAt(sb.length() - 1 - i));
sb.setCharAt(sb.length() - 1 - i, c);
}
return sb.toString();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: