字符串压缩程序

题目

通过键盘输入一串小写字母(a~z)组成的字符串。请编写一个字符串压缩程序,将字符串中连续出席的重复字母进行压缩,并输出压缩后的字符串。
压缩规则:
1、仅压缩连续重复出现的字符。比如字符串"abcbc"由于无连续重复字符,压缩后的字符串还是"abcbc"。
2、压缩字段的格式为"字符重复的次数+字符"。例如:字符串"xxxyyyyyyz"压缩后就成为"3x6yz"。

思路

用start来记录一波相同字符的起始位置,然后就是确认一个currentCharacter记录当前的这个字符,主要有两个功能,一个功能是判断是否和前一个字符相同,另一个功能就是在和前一个字符作比较,判断是否连续。如果出现了连续字符的更新,则把前一个字符的个数(当前索引减去起始索引)以及前一个字符添加到一个StringBuffer之中即可。最后就是考虑一下末尾的情况(末尾是一个单独的字符以及多个相同字符两种情况分开考虑)。

代码实现

public static String zipString(String initString){
        if(initString==null){
            return null;
        }
        if(initString.length()==0){
            return "";
        }
        int start = 0;//当前字符起始索引
        char currentCharacter=initString.charAt(0);//当前字符
        int currentIndex = 1;//当前索引
        StringBuffer sb = new StringBuffer();
        while(currentIndex<initString.length()){
            char newWord = initString.charAt(currentIndex);
            if(newWord!=currentCharacter){//更换了字符或者
                if((initString.charAt(currentIndex)-currentCharacter)!=1){
                    return initString;
                }
                if(currentIndex-start>1) {
                    sb.append(currentIndex - start);//向字符串添加数量
                }
                sb.append(currentCharacter);//添加当前字符
                currentCharacter = newWord;
                start=currentIndex;
                if(currentIndex==initString.length()-1){
                    sb.append(1);
                    sb.append(currentCharacter);
                    break;//如果已经是最后一个且是不同的字符就结束了
                }
            }
            if(currentIndex==initString.length()-1){//到字符串末尾了
                sb.append(currentIndex - start + 1);//向字符串添加数量
                sb.append(currentCharacter);//添加当前字符
            }
            currentIndex++;
        }
        return sb.toString();
    }
发布了42 篇原创文章 · 获赞 11 · 访问量 2905

猜你喜欢

转载自blog.csdn.net/weixin_41746577/article/details/104007435