Write a function that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return true if the string is valid, and false if it’s invalid.
"()" => true
")(()))" => false
"(" => false
"(())((()())())" => true
0 <= input.length <= 100
Along with opening ((
) and closing ()
)
parenthesis, input may contain any valid ASCII characters. Furthermore,
the input string may be empty and/or not contain any parentheses at all.
Do not treat other forms of brackets as parentheses (e.g. [], {},
<>).
本题的考点是 Stack 这种数据结构,先进后出,后进先出,思路如下:
function validParentheses(parens) {
let stack = [];
for (c of parens.split("")) {
if (c === '(') {
.push(c);
stackelse if (c === ')') {
} if (stack.length === 0) return false;
.pop();
stack
}
}
return stack.length === 0;
}
具体实现时,可以用整数代替栈,尽可能化简
# Valid-Parentheses.jl
using Test
"""
合法的括号
"""
#> "合法的括号\n"
function validparentheses(parens::String)::Bool
= 0
num for c in parens
# 利用短路运算,Julia 特有语法,因任何表达式都有返回值
== '(' && (num += 1)
c == ')' && (num -= 1)
c < 0 && return false
num end
== 0
num end
#> validparentheses (generic function with 1 method)
@test validparentheses("()") == true
#> Test Passed
#> Expression: validparentheses("()") == true
#> Evaluated: true == true
@test validparentheses("())") == false
#> Test Passed
#> Expression: validparentheses("())") == false
#> Evaluated: false == false
# Valid-Parentheses.R
library(tidyverse)
#' 检查括号对的匹配
<- function(parens) {
valid_parentheses <- 0
num
<- parens %>%
char_vector str_split("") %>%
unlist()
for (char in char_vector) {
if (char == "(")
<- num + 1
num if (char == ")")
<- num - 1
num if (num < 0) {
return(FALSE)
}
}
== 0
num
}
valid_parentheses("()(()())")
#> [1] TRUE
/**
* @module Valid-Parentheses
*/
/**
* 检测括号对匹配是否合法
* @param {String} parens 包含小括号和其他各种字符的字符串
* @returns {Boolean}
*/
function validParentheses(parens) {
// 用整数 stack 类比 Stack
let stack = 0;
for (c of parens.split("")) {
if (c === '(') stack++;
if (c === ')') stack--;
if (stack < 0) return false;
}
return stack === 0;
}
console.log(validParentheses("()(())"));
#> true
# Valid-Parentheses.py
#%%
def valid_parentheses(string):
"""
This is a practice problem.
It checks to see if parenthesis's are balanced
:param string: String
:return Bool:
"""
= 0
num for c in string:
if (c == "("): num += 1
if (c == ")"): num -= 1
if (num < 0): return False
return num == 0
#%%
"()")
valid_parentheses(
# %%
#> True