字符查找替换,WA了N次,一次只能替换一个,下一次find必须从第0个位置开始
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Main { /** * 镜像String,通过镜像变换后是回文String 回文String,单纯的回文String */ public static void main(String[] args) throws FileNotFoundException { //Scanner scanner = new Scanner(new File("d://1.txt")); Scanner scanner = new Scanner(System.in); while (scanner.hasNextInt()) { int testCase = scanner.nextInt(); if (testCase == 0) { break; } String[] find = new String[testCase]; String[] replace = new String[testCase]; scanner.nextLine(); for (int i = 0; i < testCase; i++) { find[i] = scanner.nextLine(); replace[i] = scanner.nextLine(); } String template = scanner.nextLine(); for (int i = 0; i < find.length; i++) { int index = -1; while ((index = template.indexOf(find[i])) != -1) { String pre = template.substring(0, index); String end = template.substring(index + find[i].length(), template.length()); template = pre + replace[i] + end; } } /// template = findAndReplace(find, replace, template); System.out.println(template); } scanner.close(); } public static String findAndReplace(String[] find, String[] replace, String template) { for (int i = 0; i < find.length; i++) { String f = find[i]; int fLength = f.length(); int length = template.length(); int s = 0, t = 0; int fIndex = 0; boolean isStart = false; for (int j = 0; j < length; j++) { if (fIndex == fLength) { t = j; break; } if (template.charAt(j) == f.charAt(fIndex)) { if (!isStart) { s = j; isStart = true; } fIndex++; continue; } if (isStart) { j = s; isStart = false; fIndex = 0; continue; } } if (isStart) { t = t == 0 ? length : t; StringBuilder sb = new StringBuilder(); for (int j = 0; j < s; j++) { sb.append(template.charAt(j)); } sb.append(replace[i]); for (int j = t; j < template.length(); j++) { sb.append(template.charAt(j)); } template = sb.toString(); } else { i++; } } return template; } }