[英]How to write a javascript function that checks if first and last characters in a string are equal
I been doing this javascript challenge and I'm pretty close, but something is off.Here's the challenge: 我一直在进行此javascript挑战,并且已经很接近了,但是有些事情发生了,这是挑战:
Given an array of strings containing three types of braces: round (), square [] and curly {} Your task is to write a function that checks whether the braces in each string are correctly matched. 给定一个包含三类花括号的字符串数组:round(),square []和curl {}您的任务是编写一个函数,检查每个字符串中的花括号是否正确匹配。 Prints 1 to standard output (console.log) if the braces in each string are matched and 0 if they're not (one result per line)
如果每个字符串中的花括号都匹配,则将1打印到标准输出(console.log);如果不匹配则将0打印(每行一个结果)
my code is this: 我的代码是这样的:
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);
The output with the current array items should be Output: 0 1 1 1 0 当前数组项的输出应为Output:0 1 1 1 0
As pointed out in the comment, only having the first and the last character same would not result in a correct solution. 正如评论中指出的那样,仅使第一个字符和最后一个字符相同将不会导致正确的解决方案。
You can try the following technique: Maintain a stack, each time you encounter an opening bracket ie round "(", square "[" or curly "{"; push this into stack. Now whenever you encounter a closing bracket, pop an element from the stack. If these two match ie both are of same type, then carry on till stack and string both are empty. If at any point these don't match then break and return false. I'll write a code for it and post it soon. 您可以尝试以下技术:维护堆栈,每次遇到开括号,即圆“(”,正方形“ [”或卷曲的“ {”;将其推入堆栈。现在,每当遇到闭合括号时,弹出一个元素如果这两个匹配,即两者都属于同一类型,则继续进行操作,直到stack和string都为空为止。如果在任何时候它们都不匹配,则中断并返回false,我将为其编写代码,然后尽快发布。
If you can use Regular Expressions, you can really slim it down: 如果可以使用正则表达式,则可以将其精简:
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);
Also, as I stated in my comment, your for syntax was off. 另外,正如我在评论中所述,您的for语法已关闭。 Oh, and instead of i+=1, you can use i++ to simplify it.
哦,您可以使用i ++代替i + = 1来简化它。
I guess you could do it in this way, keeping a "tree" of starting positions. 我想您可以通过这种方式做到,并保持起点位置的“树”。 Didn't test any other testcases than your own though :)
除了您自己的测试用例外,没有进行其他测试:)
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"); } }
or, to make it a bit easier and to check check the brackets: 或者,使其变得更简单并检查一下括号:
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.