今天刷到一个笔试题要求如下:
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 32M,其他语言64M
题目内容:
1. 三个同样的字母连在一起,一定是拼写错误,去掉一个的就好啦:比如 helllo -> hello
2. 两对一样的字母(AABB型)连在一起,一定是拼写错误,去掉第二对的一个字母就好啦:比如 helloo -> hello
3. 上面的规则优先“从左到右”匹配,即如果是AABBCC,虽然AABB和BBCC都是错误拼写,应该优先考虑修复AABB,结果为AABCC
输入描述:
第一行包括一个数字N,表示本次用例包括多少个待校验的字符串。
后面跟随N行,每行为一个待校验的字符串。
输出描述:
N行,每行包括一个被修复后的字符串。
输入例子1:
2
helloo
wooooooow
输出例子1:
hello
woow
第一种比较复杂的方法:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void question() { Scanner sc = new Scanner(System.in); // 待校验的字符串个数 int N = sc.nextInt(); // 存储输入的待校验字符串 List<String> strList = new ArrayList<>(); for (int i = 0; i < N; i++) { strList.add(sc.next()); } // 存储第一次校验的结果 List<String> firstResult = new ArrayList<>(); // 先校验三个同样的字母连在一起的情况 for (String s : strList) { boolean flag = true; while (flag) { boolean flag2 = false; for (int i = 0; i < s.length() - 2; i++) { // 判断临近三个字符是否相同 if (s.charAt(i) == s.charAt(i + 1) && s.charAt(i + 1) == s.charAt(i + 2)) { s = s.substring(0, i) + s.substring(i + 1); flag2 = true; } } if (!flag2) { // 终止循环 flag = false; } } firstResult.add(s); } // 校验两对一样的字母(AABB型)连在一起的情况 strList.clear(); for (String s : firstResult) { boolean flag = true; while (flag) { boolean flag2 = false; for (int i = 0; i < s.length() - 3; i++) { // 判断相邻四个字符是否符合AABB型 if (s.charAt(i) == s.charAt(i + 1) && s.charAt(i + 2) == s.charAt(i + 3)) { s = s.substring(0, i + 2) + s.substring(i + 3); flag2 = true; } } if (!flag2) { flag = false; } } strList.add(s); } // 输出结果 for (String s : strList) { System.out.println(s); } } }
第二种使用正则表达式:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16public class Main { public static void question() { Scanner sc = new Scanner(System.in); // 待分析的字符串个数 int N = sc.nextInt(); // 存储结果 List<String> result = new ArrayList<>(); for (int i = 0; i < N; i++) { result.add(sc.next().replaceAll("(.)\1+", "$1$1").replaceAll("(.)\1(.)\2", "$1$1$2")); } // 输出结果 for (String s : result) { System.out.println(s); } } }
最后
以上就是活力手链最近收集整理的关于面试题1:字符串校验 将错误的字符通过校验修改后使其成为正确的字符的全部内容,更多相关面试题1:字符串校验内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复