题解 | #表示数字#
表示数字
https://www.nowcoder.com/practice/637062df51674de8ba464e792d1a0ac6
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextLine()) { // 注意 while 处理多个 case String str = in.nextLine(); int start = -1; int end = -1; for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); //记住首个数字字符的位置:start if (start == -1 && (ch >= '0' && ch <= '9')) { start = i; } //判断结束位 if (ch >= '0' && ch <= '9') { if (i == str.length() - 1) { end = i; } else { //2.i不是最后一位字符,且i的下一位不是字符 char endChar = str.charAt(i + 1); if (!(endChar >= '0' && endChar <= '9')) { end = i; } } } //截取字符串进行加*,和正则替换操作 if (start != -1 && end != -1) { int length = str.length() - 1; //处理指定位置的字符 String tempc = ""; for (int j = 0; j <= length; j++) { char temp = str.charAt(j); if (start != end) { if (j == start) { tempc += ("*" + temp); } else if (j == end) { tempc += ( temp + "*"); } else { tempc += (temp + ""); } } else { if (j == start) { tempc += ("*" + temp + "*"); } else { tempc += (temp + ""); } } } str = tempc; if (i == length) { break; } else { start = -1; end = -1; //i的移位 i += 3; continue; } } } System.out.println(str); } } }
采用标记的思想,45ms,也不难。字符替换的时候需要注意一下约束条件。
正则解法(不讲武德),42ms:
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextLine()) { // 注意 while 处理多个 case String str = in.nextLine(); System.out.println(str.replaceAll("[0-9]+","*1$*"); } }