题目:https://oj.leetcode.com/problems/reverse-words-in-a-string/
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
源码:Java版本
算法分析:时间复杂度O(n),空间复杂度O(1)
public class Solution {
public String reverseWords(String s) {
char[] str=s.trim().replaceAll("\\s+", " ").toCharArray();
reverse(str,0,str.length-1);
int low=0,high=0;
while(high<str.length) {
if(str[high]!=' ') {
high++;
}else {
reverse(str,low,high-1);
high++;
low=high;
}
}
reverse(str,low,high-1);
return String.valueOf(str);
}
private void reverse(char[] str,int low,int high) {
while(low<high) {
swap(str,low++,high--);
}
}
private void swap(char[] str,int x,int y){
char temp=str[x];
str[x]=str[y];
str[y]=temp;
}
}