c# - How do I check If brackets are of same -
i check if input string contain same amount of open/close brackets. if yes print out true else false. have wrote code there bug can help?
see code works fine if enter string '()' starts open bracket , ends close bracket if enter ')(' still prints out true?. output should be:
() = true (())=true ()) = false (() = false )( = false )(() = false etc...
thanks help
edit:
using system; public class program { public void main() { checkparentheses ("()"); } public void checkparentheses (string inputparentheses){ int openparentheses = 0; int closeparentheses = 0; (int = 0; < inputparentheses.length; i++) { if (inputparentheses[i] == '(') { openparentheses++; } if (inputparentheses[i] == ')') { closeparentheses++; } if (openparentheses == closeparentheses) console.writeline("true"); } } }
instead of counting open/close parenthesys check order
public void checkparentheses(string inputparentheses) { // level counter int parenlevel = 0; (int = 0; < inputparentheses.length; i++) { // open good, increment level if (inputparentheses[i] == '(') parenlevel++; else if (inputparentheses[i] == ')') parenlevel--; // closing good, if level doesn't drop under 0 if (parenlevel < 0) { console.writeline("false"); return; } } // @ end of loop, level should 0 if(parenlevel != 0) console.writeline("false"); else console.writeline("true"); }
Comments
Post a Comment