剑指 Offer 58 - I. 翻转单词顺序

https://leetcode-cn.com/problems/fan-zhuan-dan-ci-shun-xu-lcof/

双指针法

 public String reverseWords(String s) {
       s = s.trim();
       int j=s.length()-1,i=j;
       StringBuffer sb = new StringBuffer();
       while (i>=0){
           while (i>=0&&s.charAt(i)!=' ')i--;
           sb.append(s.substring(i+1,j+1)+" ");
           while (i>=0&&s.charAt(i)== ' ')i--;
           j=i;
       }
       return sb.toString().trim();
    }
   
  

你可能感兴趣的:(leetcode)