Reverse Words in a String [Medium]

来源:互联网 发布:怎样查看udp端口 编辑:程序博客网 时间:2024/05/02 21:26

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.

Clarification:

  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.

===================================================Answer ==================================================
public class Solution {    public String reverseWords(String s) {                if(s==null) return null;                if(s.trim().length()==0) return s.trim();                s=s.trim();                String[] tempArr = new String[s.length()];        StringBuilder sb = new StringBuilder();        char[] charArr = s.toCharArray();        int tempArrIndex= 0;                for(int i=0;i<charArr.length;i++) {            char c=charArr[i];                        if(c!=' ') {                sb.append(c);                                if(i==charArr.length-1){                    tempArr[tempArrIndex]=sb.toString();                    sb.setLength(0);                    tempArrIndex++;                }            }                        else if(c==' '&& sb.length()>0) {                tempArr[tempArrIndex]=sb.toString();                sb.setLength(0);                tempArrIndex++;                continue;            }        }                for(int i=tempArrIndex-1;i>=0;i--) {            sb.append(tempArr[i]).append(' ');        }                return sb.toString().trim();            }}




0 0
原创粉丝点击