Medium 151题 Reverse Words in a String

来源:互联网 发布:戴尔公司待遇 知乎 编辑:程序博客网 时间:2024/05/17 17:44

Question:

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

For example,
Given s = "the sky is blue",
return "blue is sky the".


Solution:

String[] parts = s.trim().split("\\s+");String out = "";for (int i = parts.length - 1; i > 0; i--) {    out += parts[i] + " ";}return out + parts[0];

比较复杂但是效率高的算法

public class Solution {    public String reverseWords(String s) {        if(s.trim().length()==1)return s.trim();StringBuilder sb=new StringBuilder();        for(int i = s.length()-1;i>=0;i--)        {        if(s.charAt(i)==' ')        {        continue;        }        int end =i;        while(s.charAt(i)!=' '&& i>=1)        i--;        if(s.charAt(i)==' ')        sb=sb.append(s.substring(i+1, end+1)).append(" ");        else        sb=sb.append(s.substring(i, end+1)).append(" ");        }        return sb.toString().trim();    }}

二刷稍微改进了下

public class Solution {    public String reverseWords(String s) {        StringBuilder sb=new StringBuilder();        if(s.trim().length()==1)            return s.trim();        int end=0;        for(int i=s.length()-1;i>=0;i--)        {            while(s.charAt(i)==' '&&i>=1)                i--;            end=i;            while(s.charAt(i)!=' '&&i>=1)                i--;            if(s.charAt(i)==' ')                sb.append(s.substring(i+1,end+1)).append(" ");            else                 sb.append(s.substring(i,end+1))//.append(" ");i==1的情况        }        return sb.toString().trim();    }}


0 0
原创粉丝点击