您的位置:首页 > 其它

Reverse Words

2015-07-13 08:10 281 查看
Reverse Words

Write a function that reverses the order of the words in a string. For example
4000
, your function should transform the string “Do or do not, there is no try.” to “try. no is there not, do or Do”. Assume that all words are space delimited
and treat punctuation the same as letters.

class Solution {
public static String reverseWords(char[] str) {
if (str == null || str.length == 0)
return null;

reverseStr(str, 0, str.length - 1);

int start = 0;
int end = 0;
while (end < str.length) {
if (str[end] != ' ') {
start = end;

while ( end < str.length && str[end] != ' ')
end++;

end--;
reverseStr(str, start, end);

}
end++;
}

return new String(str);
}

private static void reverseStr(char[] str, int start, int end) {

while (end > start) {

char temp = str[start];
str[start] = str[end];
str[end] = temp;

end--;
start++;
}

}
public static void main(String[] args) {
String str = "Do or do not, there is no try.";
char[] ch = str.toCharArray();
System.out.print(reverseWords(ch));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: