牛客网 2018校招真题 爱奇艺 缺失的括号

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32767041/article/details/86516243

Description

牛客网 2018校招真题 缺失的括号

Solving Ideas

使用辅助栈

  • 当遇到'('时,将其压入栈中,因为需要一个')'才能使括号字符串完整,所以count++
  • 当遇到')'时,如果栈空,说明需要添加一个(才能使括号字符串完整,所以count++;如果栈不空,说明栈中的'('有匹配的')',所以count–;

Time complexity : O ( n ) O(n)
Space complexity : O ( n ) O(n)

Solution

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;

/**
 * @author wylu
 */
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        char[] str = br.readLine().toCharArray();

        LinkedList<Character> stack = new LinkedList<>();
        int count = 0;
        for (char ch : str) {
            if (ch == '(') {
                stack.push('(');
                count++;
            } else {
                if (stack.isEmpty()) {
                    count++;
                } else {
                    count--;
                    stack.pop();
                }
            }
        }
        System.out.println(count);
    }
}

优化,将空间复杂度降至 O ( 1 ) O(1)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author wylu
 */
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        char[] str = br.readLine().toCharArray();

        int res = 0, count = 0;
        for (char ch : str) {
            if (ch == '(') {
                count++;
                res++;
            } else {
                if (count == 0) {
                    res++;
                } else {
                    res--;
                    count--; //匹配一个左括号
                }
            }
        }
        System.out.println(res);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_32767041/article/details/86516243
今日推荐