首页 > 试题广场 >

括号字符串的有效性

[编程题]括号字符串的有效性
  • 热度指数:7337 时间限制:C/C++ 2秒,其他语言4秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一个字符串str,判断是不是整体有效的括号字符串(整体有效:即存在一种括号匹配方案,使每个括号字符均能找到对应的反向括号,且字符串中不包含非括号字符)。

数据范围:

输入描述:
输入包含一行,代表str


输出描述:
输出一行,如果str是整体有效的括号字符串,请输出“YES”,否则输出“NO”。
示例1

输入

(()) 

输出

YES 
示例2

输入

()a() 

输出

NO 

说明

()a()中包含了 ‘a’,a不是括号字符    

备注:
时间复杂度,额外空间复杂度
时间复杂度O(n),n为字符串的长度;空间复杂度O(1)。
count计数
- 遇到左括号 count++
- 遇到右括号 count--。如果count为负数,返回false
- 遇到其他字符返回false
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.next();
        System.out.println(check(s) ? "YES": "NO");
    }

    private static boolean check(String s) {
        if (s == null || s.length() == 0) return false;
        int count = 0;
        for (int i = 0; i < s.length(); ++i) {
            if (s.charAt(i) == '(') {
                count++;
            } else if (s.charAt(i) == ')'){
                if (--count < 0) {
                    return false;
                }
            } else {
                return false;
            }
        }
        return count == 0;
    }

}


发表于 2021-08-10 17:30:20 回复(0)
import java.util.*;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while (sc.hasNext()) {
			String input = sc.nextLine();
			boolean res = validBracket(input);
			if (res) {
				System.out.println("YES");
			} else {
				System.out.println("NO");
			}
		}
	}

	public static boolean validBracket(String input) {
		// Corner case
		if (input == null || input.length() == 0) {
			return true;
		}
		if (input.length() % 2 != 0) {
			return false;
		}
		char[] array = input.toCharArray();
		// Use a stack
		LinkedList<Character> stack = new LinkedList<>();
		for (int i = 0; i < array.length; i++) {
			if (array[i] == '(') {
				stack.push(array[i]);
			} else if (array[i] == ')') {
				if (!stack.isEmpty() && stack.peek() == '(') {
					stack.pop();
				} else {
					return false;
				}
			} else {
				return false;
			}
		}
		// Post Processing
		return stack.isEmpty();
	}
}

发表于 2019-11-27 17:35:03 回复(0)