简体   繁体   中英

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:

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. 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)

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

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.

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. Oh, and instead of i+=1, you can use i++ to simplify it.

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'); } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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