美文网首页
三元运算符(Leetcode 439)

三元运算符(Leetcode 439)

作者: 抬头挺胸才算活着 | 来源:发表于2021-09-27 10:09 被阅读0次

    思路:
    递归分解的思路很简单,但每次都要遍历整个string看?对应的:在哪里,因此可以先一边遍历一边使用栈记录问号?对应的分号:在哪里,这样就减少了每次遍历。
    输入:“T?2:3”
    输出:“2”
    输入: “F?1:T?4:5”
    输出: “4”
    输入:″T?T?F:5:3″
    输出: “F”

        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            String line = scanner.nextLine();
    
            System.out.println(calcExpress(line));
        }
    
        private static String calcExpress(String line) {
            int[] semicolonIndexes = new int[line.length()];
            Stack<Integer> stack = new Stack<>();
    
            for (int i = 0; i < line.length(); i++) {
                char ch = line.charAt(i);
                if (ch == '?') {
                    stack.push(i);
                } else if (ch == ':') {
                    int questionMarkIndex = stack.pop();
                    semicolonIndexes[questionMarkIndex] = i;
                } else {
                    continue;
                }
            }
    
            return calcExpress(line, semicolonIndexes, 0, line.length());
        }
    
        private static String calcExpress(String line, int[] semicolonIndexes, int start, int end) {
            if (end - start == 1) {
                return line.substring(start, end);
            }
    
            for (int i = start; i < end; i++) {
                char ch = line.charAt(i);
    
                if (ch == '?') {
                    int semicolonIndex = semicolonIndexes[i];
                    return line.charAt(i - 1) == 'T' ? calcExpress(line, semicolonIndexes, i + 1,
                        semicolonIndex) : calcExpress(line, semicolonIndexes, semicolonIndex + 1, end);
                }
            }
    
            return "impossible result";
        }
    

    相关文章

      网友评论

          本文标题:三元运算符(Leetcode 439)

          本文链接:https://www.haomeiwen.com/subject/sishnltx.html