leetcode 151. Reverse Words in a String

来源:互联网 发布:淘宝店铺如何优化 编辑:程序博客网 时间:2024/06/18 13:59

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

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

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

click to show clarification.

Subscribe to see which companies asked this question.

public class Solution {    public String reverseWords(String s) {        if(s.length()==0) return s;        String[] words=s.split(" ");        String str="";        LinkedList<String> list=new LinkedList<>();        for(int i=0;i<words.length;i++){            if(words[i].length()>0)list.addFirst(words[i]);        }        for(int i=0;i<list.size()-1;i++){            str=str+list.get(i)+" ";        }        if(list.size()>0){            str=str+list.get(list.size()-1);        }        return str;    }}

0 0
原创粉丝点击