Java代码实现括号匹配检查 - 数组物理结构应用
package\ project3;import\ java.util.*;public\ class\ class4\ {public\ static\ void\ main(String[]\ args)\ {try\ (Scanner\ scanner\ =\ new\ Scanner(System.in))\ {System.out.println("请输入包含有花括号{}、中括号[]、小括号()的字符串:");String\ input\ =\ scanner.nextLine();boolean\ isMatched\ =\ isBracketMatched(input);if\ (isMatched)\ {System.out.println("括号匹配正确");}else\ {System.out.println("括号匹配错误");}}public\ static\ boolean\ isBracketMatched(String\ input)\ {int\ count\ =\ 0;for\ (char\ c\ :\ input.toCharArray())\ {if\ (c\ ==\ '{'\ ||\ c\ ==\ '['\ ||\ c\ ==\ '(')\ {count++;}else\ if\ (c\ ==\ '}'\ ||\ c\ ==\ ']'\ ||\ c\ ==\ ')')\ {if\ (count\ ==\ 0)\ {return\ false;}}count--;}}return\ count\ ==\ 0;}}在这个代码中,采用的是数组的物理结构。代码中的字符串被转换为字符数组,通过遍历字符数组来进行括号匹配的检查。
原文地址: https://www.cveoy.top/t/topic/psab 著作权归作者所有。请勿转载和采集!