繁体   English   中英

如何编写一个JavaScript函数来检查字符串中的第一个和最后一个字符是否相等

[英]How to write a javascript function that checks if first and last characters in a string are equal

我一直在进行此javascript挑战,并且已经很接近了,但是有些事情发生了,这是挑战:

给定一个包含三类花括号的字符串数组:round(),square []和curl {}您的任务是编写一个函数,检查每个字符串中的花括号是否正确匹配。 如果每个字符串中的花括号都匹配,则将1打印到标准输出(console.log);如果不匹配则将0打印(每行一个结果)

我的代码是这样的:

var infoToParse = [ ")(){}", "[]({})", "([])", "{()[]}", "([)]" ]; 

function checkBraces(infoToParse) {
    var tabChars = infoToParse;
    for (i= 0; tabChars.length - 1; i+=1) {
        if (tabChars[i].charAt(0) === tabChars[i].charAt(tabChars[i].length-1)){
            console.log(1);
        }else{
            console.log(0);
        }
    }
}

checkBraces(infoToParse);

当前数组项的输出应为Output:0 1 1 1 0

正如评论中指出的那样,仅使第一个字符和最后一个字符相同将不会导致正确的解决方案。

您可以尝试以下技术:维护堆栈,每次遇到开括号,即圆“(”,正方形“ [”或卷曲的“ {”;将其推入堆栈。现在,每当遇到闭合括号时,弹出一个元素如果这两个匹配,即两者都属于同一类型,则继续进行操作,直到stack和string都为空为止。如果在任何时候它们都不匹配,则中断并返回false,我将为其编写代码,然后尽快发布。

如果可以使用正则表达式,则可以将其精简:

var stringArray = [ ")(){}", "[]({})", "([])", "{()[]}", "([)]" ]; 

function checkBraces(infoToParse) {
    for (i = 0; i < infoToParse.length; i += 1) {
    var regX = /^\[.*\]$|^\{.*\}$|^\(.*\)$/gi;
    var str = infoToParse[i];
    console.log(str.match(regX) ? 1 : 0);
    }
}

checkBraces(stringArray);

另外,正如我在评论中所述,您的for语法已关闭。 哦,您可以使用i ++代替i + = 1来简化它。

我想您可以通过这种方式做到,并保持起点位置的“树”。 除了您自己的测试用例外,没有进行其他测试:)

 var testCases = [")(){}", "[]({})", "([])", "{()[]}", "([)]"]; var braceType = { round: ["(", ")"], curly: ["{", "}"], square: ["[", "]"] }; var bracePosition = { start: ["{", "(", "["], end: ["}", ")", "]"] }; function typeOfBraces(sign) { for (var property in braceType) { if (braceType[property].indexOf(sign) < 0) { continue; } if (bracePosition.start.indexOf(sign) < 0) { return { type: property, position: "end" }; } else { return { type: property, position: "start" }; } } throw "Sign is not a brace!"; }; function Braces(brace, parent, type) { this.brace = brace; this.parent = parent || null; this.type = type || { type: 'init', position: '' }; this.children = []; this.nextBrace = function(nextSign) { var nextType = typeOfBraces(nextSign); if (nextType.position === 'start') { var child = new Braces(nextSign, this, nextType); this.children.push(child); return child; } if (nextType.position === 'end') { if (this.type.position === '') { throw 'Cannot start with an end tag!'; } if (this.type.position === 'end' && this.parent === null) { throw 'Cannot end the sequence'; } if (this.type.position === 'end' && this.parent.position === 'start') { if (this.type.type === this.parent.type) { var child = new Braces(nextSign, this.parent, nextType); this.parent.children.add(child); return this.parent; } } } if (this.type.position === 'start' && nextType.type === this.type.type && nextType.position === 'end') { return this.parent; } return new Braces(nextSign, this, nextType); }; } for (var i = 0; i < testCases.length; i++) { var brace = new Braces(testCases[i]); for (var j = 0, len = testCases[i].length; j < len; j++) { try { brace = brace.nextBrace(testCases[i][j]); } catch (e) { console.log(e); brace = null; break; } } if (brace != null && brace.parent == null) { // valid entry console.log(brace); console.log(testCases[i] + " is a valid sequence"); } else { // invalid entry console.log(testCases[i] + " is an invalid sequence"); } } 

或者,使其变得更简单并检查一下括号:

 function validBraces(braceSequence) { var stack = '', i, len, lastStack = -1, toAdd = "{([", toRemove = "})]", sign; for (i = 0, len = braceSequence.length; i < len; i++) { sign = braceSequence[i]; if (toAdd.indexOf(sign) >= 0) { stack += sign; lastStack++; } else if (toRemove.indexOf(sign) >= 0) { if (toAdd.indexOf(stack.charAt(lastStack)) !== toRemove.indexOf(sign)) { // format exception console.warn('Format exception, didn\\'t expect ' + sign + ' (current stack: ' + stack + ')'); return false; } else { stack = stack.slice(0, -1); lastStack--; } } else { console.warn('Invalid character exception, didn\\'t expect ' + sign + ' (current stack: ' + stack + ')'); return false; } } return true; } var testCases = [")(){}", "[]({})", "([])", "{()[]}", "([)]"]; for (var i = 0; i < testCases.length; i++) { if (validBraces(testCases[i])) { console.log(testCases[i] + ' is a valid sequence'); } else { console.log(testCases[i] + ' is an invalid sequence'); } } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM