笔试笔记————基本字符串压缩

来源:互联网 发布:音箱分频器设计软件 编辑:程序博客网 时间:2024/04/29 19:11

利用字符重复出现的次数,编写一个方法,实现基本的字符串压缩功能。比如,字符串“aabcccccaaa”经压缩会变成“a2b1c5a3”。若压缩后的字符串没有变短,则返回原先的字符串。

给定一个string iniString为待压缩的串(长度小于等于10000),保证串内字符均由大小写英文字母组成,返回一个string,为所求的压缩后或未变化的串。

测试样例
"aabcccccaaa"
返回:"a2b1c5a3"
"welcometonowcoderrrrr"
返回:"welcometonowcoderrrrr"

我的思路:从头开始计算比较相同的字符,相等则计数器+1,直到碰到不等的为止;下一次从源+计数器的值(即不等的下一位)开始比较,循环比较。最后再比较两字符串长度。

import java.util.*;public class Zipper {    public String zipString(String iniString) {        // write code here        int l = iniString.length();        String str = new String();        for(int i = 0; i < l; i++){            int count = 0;            for(int j = i; j < l; j++){                if(iniString.charAt(i) == iniString.charAt(j)){                    count++;                }else {                    break;                }            }            str += iniString.charAt(i) + String.valueOf(count);            i += count - 1;        }        if(iniString.length() >= str.length()){            return str;        }else return iniString;    }}


0 0
原创粉丝点击