题解 | 倒置字符串

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String line = in.nextLine();
            String reverseStr = process(line);
            System.out.println(reverseStr);
        }
    }

    private static String process(String s) {
        Stack<String> sk = new Stack<>(); 
        StringBuilder sb = new StringBuilder();
        int end = 0;
        int start = 0;
        while (end < s.length()) {
            char c = s.charAt(end);
            if (c == ' ') {
                // 将 start 至 end 这段字符串 放入栈中
                String sub = s.substring(start, end);
                sk.push(sub);
                start = end + 1;       
            } 
            end++;
        }
        String sub = s.substring(start, end); // 最后一段 不要遗漏
        sk.push(sub);
        while(!sk.isEmpty()) {
            sb.append(sk.pop()); 
            sb.append(" ");
        }
        sb.deleteCharAt(sb.length()-1);
        return sb.toString();
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务