算法:有效括号
13122256420
663
2024-02-26

给定 “()[] {}” 的字符串,判断是否是闭合标签

输入:()[]{}  输出:true

输入:([]){}  输出:true

输入:([]{)}  输出:false


js版本
console.log(is_valid("([])"))

function is_valid(str) {
    let arr = []
    for (let i = 0; i < str.length; i++) {
        console.log(str[i])
        if (str[i] === "(") {
            arr.push(")")
        } else if (str[i] === "[") {
            arr.push("]")
        } else if (str[i] === "{") {
            arr.push("}")
        } else if (arr.length === 0 || str[i] !== arr.pop()) {
            return false
        }
    }

    return arr.length === 0
}
go版本
func is_valid() {
	var bools = true
	var str = "([])"
	var arr []string
	for i := 0; i < len(str); i++ {
		fmt.Println(string(str[i]), arr)
		var m = string(str[i])
		if m == "(" {
			arr = append(arr, ")")
		} else if m == "[" {
			arr = append(arr, "]")
		} else if m == "{" {
			arr = append(arr, "}")
		} else if len(arr) == 0 {
			if m != arr[len(arr)-1] {
				bools = false
			}
			arr = arr[:len(arr)-1]
		}
	}
	fmt.Println(bools)
}
rust版本
fn is_valid() {
    let mut bools = true;
    let str = "([])";
    let charsStr: Vec<char> = str.chars().collect();
    let mut vec1: Vec<char> = Vec::new();
    for i in 0..charsStr.len() {
        println!("{}", charsStr[i]);
        if charsStr[i] == '(' {
            vec1.push(')')
        } else if charsStr[i] == '[' {
            vec1.push(']')
        } else if charsStr[i] == '{' {
            vec1.push('}')
        } else if vec1.is_empty() || charsStr[i] != vec1.pop().unwrap() {
            bools = false
        }
    }

    println!("{}", bools)
}