Efficiently reverse the order of the words (not characters) in an array of characters

前端 未结 21 1882
[愿得一人]
[愿得一人] 2020-11-28 04:40

Given an array of characters which forms a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it.

Example input and

21条回答
  •  [愿得一人]
    2020-11-28 05:06

    Algorithm: 1).Reverse each word of the string. 2).Reverse resultant String.

    public class Solution {
    public String reverseWords(String p) {
       String reg=" ";
      if(p==null||p.length()==0||p.equals(""))
    {
        return "";
    }
    String[] a=p.split("\\s+");
    StringBuilder res=new StringBuilder();;
    for(int i=0;i

提交回复
热议问题