LeetCode-Reverse Words in a String

来源:互联网 发布:花洒推荐 知乎 编辑:程序博客网 时间:2024/06/06 06:56

题目: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".

click to show clarification.

分析:两次翻转法,第一次翻转整个句子,第二次翻转每个单词。

源码: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;    }}

0 0
原创粉丝点击