题目: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;
}
}
本文介绍了使用Java语言解决字符串中单词反转的问题,通过两次翻转实现,详细解释了算法的实现过程及时间、空间复杂度。
297

被折叠的 条评论
为什么被折叠?



