javascript中的字符串比较特殊字符



以下函数的输入字符串为:"()[]{}"

var isValid = function(s) {
if ((s.length == 2 && s[0] == s[1]) || s.trim().length == 0) {
return true;
}
if (s.length % 2 != 0) {
return false;
}
for (let i = s.length / 2, j = i - 1; i < s.length && j >= 0; i++, j--) {
console.log(s[j], s[i])
if (s[i].charCodeAt(0) !== s[j].charCodeAt(0)) {
console.log("false", s[j].length, s[i].length)
return false;
}
}
return true;
};

当它比较[和]时,它在for循环中进入if条件并返回false。

我试着比较s[i] != s[j]仍然是同样的问题。

描述:

给定一个仅包含字符"(","(","{","}"、"["one_answers"]"的字符串,请确定输入字符串是否有效。

输入字符串在以下情况下有效:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.

请注意,空字符串也被认为是有效的。

Example 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false

使用Regex使验证更加容易。验证将检查/(((|{}|[](/g,当找到((、{}或[]时,将其从字符串中删除,直到字符串为空。

假设我们有一个字符串"([]({}{[]}((">,那么函数要做的就是不断删除((、{}或[]直到删除所有字符串。如果循环结束后字符串不为空,则意味着存在多余的(,{或[。函数看不到((、{}或[]。当它们是外部的时,只需不断删除内部,直到外部变成内部。

function validParentheses(parens) {
while(/(()|{}|[])/g.test(parens)) parens = parens.replace(/(()|{}|[])/g, '');
return parens ? false : true;
}
console.log(validParentheses('(([{}]){}[])()'));

您可以这样尝试。在这里,我删除了您编写的代码的许多部分,并使其发挥作用。

注意:由于JavaScript的对象在搜索时速度很快,所以我过去常常映射相关的括号。代码很简单,所以我没有添加注释。

您也可以在https://rextester.com/CJMZ17507.

//nodejs v4.2.6
var brackets = {
"(": ")",
"[": "]",
"{": "}"
}
var isValid = function(s) {
var valid = false
var index = 0
if(s.length % 2 !== 0)
return false
while(index < s.length -1){
ch = s[index]
if(ch in brackets) {
if(brackets[ch] === s[index + 1]) {
index += 2
valid = true
continue
} else {
valid = false
break
}
} else {
valid = false
break
}
}
if(valid === false && s.length === 0) {
valid = true
}
return valid;
};
console.log(isValid("[]{}()")) // true
console.log(isValid("[]")) // true
console.log(isValid("")) // true
console.log(isValid("[]{})")) // false
console.log(isValid("[]}{")) // false
console.log(isValid("[]{}(())")) // false
console.log(isValid("([)]")) // false
console.log(isValid("(]")) // false

对于简单的测试用例,它就像在数组上循环两个字符并查看字符是否匹配一样简单

var oppBracket = {
'(': ')',
'{': '}',
'[': ']'
}
function test(str) {
// loop over the array by twos
for (var i = 0; i < str.length; i += 2) {
// grab the closing bracket that matches the opening bracket
var opp = oppBracket[str[i]]
// if we do not have a closing bracket it is false
// if the next index does not match the closing we found, it fails
if (!opp || opp !== str[i + 1]) return false
}
// if we get here, all the pairs matched
return true
}
console.log(test("()"))
console.log(test("()[]{}"))
console.log(test("()[]}{"))

在现实世界的测试用例中,它可能被嵌套,并且该方法会失败。所以这是一个简单的弹出式

var openBracket = {
'(': ')',
'{': '}',
'[': ']'
}
function test(str) {
// opens will hold all the brackets that are not matched
var opens = []
// Loop over all the characters in the string
for (var i = 0; i < str.length; i++) {
// grab the current character
var current = str[i]
// see if it is an opening bracket
var open = openBracket[current]
if (open) {
// if it is push the closing character onto the stack of unclosed brackets
opens.push(open)
} else {
// if it is pop off the last open bracket
var expecting = opens.pop()
// see if the current closing bracket matches the last open
if (current !== expecting) {
// if it does not the test fails
return false
}
}
}
// if we make it here, all the brackets were closed if array is empty
return opens.length === 0
}
console.log(test("()"))
console.log(test("()[]{}"))
console.log(test("()[]}{"))
console.log(test("(((([]{}))))"))
console.log(test("(((((((((("))

这里的字符串输入可以是空的",也可以是"(','("、"{','}"、"["、"]]"的组合。因此,首先取一个空的数组。当打开的字符即将推送到数组时,开始迭代循环中输入字符串的所有字符。稍后,当任何闭合字符首先出现时,请检查该条目的打开字符(,例如"["条目的打开的字符"]">(是否存在于数组中,并且它必须是数组的最后一个条目。如果发现,则弹出。检查所有迭代后,如果数组为空,则返回true,否则返回false

var isValid = function(s){
var arr = [];
for(var i = 0; i<s.length; i++){
if(s[i] === '(' || s[i] === '{' || s[i] === '[') arr.push(s[i]);
else{
if(arr.length === 0) return false;
switch(s[i]){
case ')':
if(arr[arr.length-1]  === '(') arr.pop();
break;
case '}':
if(arr[arr.length-1]  === '{') arr.pop();
break;
case ']':
if(arr[arr.length-1]  === '[') arr.pop();
break;
}
}
}
if(arr.length === 0) return true;
return false;
}

最新更新