-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
javascript 有效括号 #19
Labels
Comments
function isValid(str) {
const stack = []
const parentheses = str.split('')
for (let i = 0; i < parentheses.length; i++) {
const x = parentheses[i]
switch (x) {
case '{':
case '(':
stack.push(x)
break
case ')':
if (stack.pop() !== '(') {
return false
}
break;
case '}':
if (stack.pop() !== '{') {
return false
}
break;
}
}
if (stack.length) {
return false
}
return true
} |
function match(str) {
const stack = [];
for (let char of str) {
if (char === '(' || char === '{') {
stack.push(char);
} else if (char === ')' && stack.pop() !== '(') {
return false;
} else if (char === '}' && stack.pop() !== '{') {
return false;
}
}
return stack.length === 0;
} |
function isOk(str) {
let obj = {
'(': ')',
'{': '}'
}
let arr = str.split('').reduce((a, b, i) => {
let len = a.length;
let left = a[len - 1];
if (obj[left] === b) {
let p = a.pop()
} else {
a.push(b)
}
return a;
}, [])
return !arr.length;
} |
function checkStr(str) {
let length = str.length
if (length === 0 || length % 2 !== 0) {
return false
}
let slcount = 0
let srcount = 0
let blcount = 0
let brcount = 0
for(let i = 0; i < length; i++) {
switch(str[i]) {
case '(':
slcount ++
break
case ')':
srcount ++
break
case '}':
blcount ++
break
case '{':
brcount ++
break
}
}
if(slcount !== srcount || blcount !== brcount) {
return false
}
let reg = /^(\)|\})|(\(|\{)$/g
if(reg.test(str)) {
return false
}
if(str.indexOf('{)')>-1 || str.indexOf('(}')>-1) {
return false
}
return true
} |
function isVaild(){
let args = Array.prototype.slice.call(arguments),
previous = args[0],
need_check_string = args[1] ? args[1] : args[0]
need_check_string = need_check_string.replace(/\(\)/g,'').replace(/{}/g,'')
if(!need_check_string) return true
if(previous === need_check_string) return false
previous = need_check_string
return isVaild(previous,need_check_string)
}
let TestArray = ["()" ,"(",")(" ,")(()))","(())((()())())","(({}))((({})({}))())","(({}))((({)}({}))())"]
TestArray.forEach(t => console.log(t.padEnd(30,' ') + `==> ${isVaild(t)}`)) |
function V1(input) {
function calc(str) {
let s = str.replace(/(\(\))|(\{\})/g, '');
if (!s) {
return true;
}
if (str.length === s.length) {
return false;
}
return calc(s);
}
return calc(input);
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
编写一个函数,并确定括号(包括大括号与小括号)的顺序和组合是否有效。
如果字符串有效,函数应该返回true,如果无效则返回false。
字符串长度大于0。
The text was updated successfully, but these errors were encountered: