ACM试题题源(括号配对问题):http://acm.nyist.net/JudgeOnline/problem.php?pid=2
提交代码:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner cin = new Scanner(System.in); int n = cin.nextInt(); String[] ans = new String[n]; for (int i = 0; i < n; i++) { ans[i] = cin.next(); String res = ""; for(int j =0;j<ans[i].length();j++){ if(res.isEmpty()){ res = res + ans[i].substring(j, j+1); }else if(res.charAt(res.length()-1)==‘(‘&&ans[i].charAt(j)==‘)‘||(res.charAt(res.length()-1)==‘[‘&&ans[i].charAt(j)==‘]‘)){ res = res.substring(0,res.length()-1); }else{ res = res + ans[i].substring(j, j+1); } } if(res.isEmpty()){ ans[i] = "Yes"; }else { ans[i] = "No"; } } for(int i = 0 ;i<ans.length;i++){ System.out.println(ans[i]); } } }
总结:
注意String.charAt(int index)和Sring.substring(int beg, int end)中的参数值,也就是下标怎么取,例如:
String str = "abcde"; System.out.println(str.charAt(0)) // 输出:a(单个字符) System.out.println(str.charAt(2)) // 输出:c(单个字符) System.out.println(str.substring(0,1)) // 输出:a(字符串) System.out.println(str.substring(1,3)) // 输出:bc(字符串)
ACM试题 - 括号配对问题 - Java中字符串截取和定位问题
时间: 2024-10-12 20:57:38