题解 | #句子逆序#

句子逆序

http://www.nowcoder.com/practice/48b3cb4e3c694d9da5526e6255bb73c3

一种便于理解的伪双指针解法

import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String str = sc.nextLine();
            int len = str.length();
            StringBuilder ans = new StringBuilder();
            int left = 0, right = len - 1;
            //清除左边空格
            while(str.charAt(left) == ' '){
                left++;
            }
            //清除右边空格
            while(str.charAt(right) == ' '){
                right--;
            }
            
            //开始添加单词
            while(left <= right){
                int index = right;
                //index 向左遍历找到第一个空格后停下
                while(index >= left && str.charAt(index) != ' '){
                    index--;
                }
                //锁定遍历单词的起始位置
                for(int i = index + 1; i <= right; i++){
                    ans.append(str.charAt(i));
                }
                //判断如果不是最后一个单词,就添加一个空格
                if(index > left){
                    ans.append(' ');
                }
                
                 //使用 index 指针 跳过中间可能出现的空格
                while(index >= left && str.charAt(index) ==' '){
                    index--;
                }
                // 把 right 放到下一个单词出现的位置,继续循环
                right = index;
            }
            System.out.print(ans.toString());
        }
    }
}
全部评论

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务