算法编程(Java)#校对程序

版权声明:作者:xp_9512 来源:CSDN 版权声明:本文为博主原创文章,转载请附上博文链接! 原文: https://blog.csdn.net/qq_40981804/article/details/89560022

问题描述

实现一个单词校对程序,实现以下几个功能:

  • 如果有三个同样的字母连在一起,则需要去掉一个,如’helllo’ -> ‘hello’

  • 如果有两对同样的字母(AABB型)连在一起,去掉第二对的一个字母,如’helloo’ -> ‘hello’

  • 上面的规则都必须优先从左到右匹配,如’AABBCC’,要先处理第一个’AABB’,结果为’AABCC’

输入

输入描述:
第一行包含一个数字n,表示本次用例包括多少个待校验的字符串
之后n行,每行为一个待校验的字符串。
输出描述:
n行,每行包括一个被修复后的字符串
示例1:
输入:
2
helloo
wooooooooow
输出:
hello
woow

代码

public class test2 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        ArrayList<String> arrayList = new ArrayList<String>();
        for (int i = 0; i < n; i++) {
            arrayList.add(sc.next());
        }
        for (String s : arrayList) {
            s = checkString(s);
            System.out.println(s);
        }
 
    }
 
    //检查字符串
    private static String checkString(String s) {
        String s2;
        StringBuffer s1 = new StringBuffer(s);
        //检查连续三个字母一样
        for (int i = 0; i < s1.length() - 2; i++) {
            if ((s1.charAt(i) == s1.charAt(i + 1)) && (s1.charAt(i) == s1.charAt(i + 2))) {
                s1.deleteCharAt(i);
                i--;
            }
        }
        //检查AABB型
        for (int i = 0; i < s1.length() - 3; i++) {
            if ((s1.charAt(i) == s1.charAt(i + 1)) && (s1.charAt(i+2) == s1.charAt(i + 3))) {
                s1.deleteCharAt(i+2);
                i--;
            }
        }
        s2 = s1.toString();
        return s2;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40981804/article/details/89560022