美文网首页
字符串压缩

字符串压缩

作者: 历十九喵喵喵 | 来源:发表于2020-11-30 12:05 被阅读0次

字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaaa会变为a2b1c5a3。若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)。

解法:

用双指针。

一个i 指向第一个元素,一个 j 指向第二个元素,比较 j 所指的元素是否等于 i 指向的元素,如果相等,则进行记录,且 j 往后移继续比较,当 j 所指向的元素不再相等时, 令 i = j ,开始新的元素的比较与计数。

关键:用什么来记录并连接成字符串然后输出?

答案: 用 StringBuilder,用于单线程的可变序列。

用到的方法有:

append():This method appends the string representation of the X type argument to the sequence.

char charAt(int index): This method returns the char value in this sequence at the specified index.

String toString(): This method returns a new String that contains a subsequence of characters currently contained in this character sequence.

int length(): This method returns the length (character count).

附上代码:

public String compressString(String S) {

    int N = S.length();

    int i = 0;

    StringBuilder sb = new StringBuilder();

    while (i < N) {

        int j = i;

        while (j < N && S.charAt(j) == S.charAt(i)) {

            j++;

        }

        sb.append(S.charAt(i));

        sb.append(j - i);

        i = j;

    }

    String res = sb.toString();

    if (res.length() < S.length()) {

        return res;

    } else {

        return S;

    }

}

作者:nettee

链接:力扣

相关文章

  • 1394-字符串压缩

    字符串压缩 题目 字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabc...

  • LeetCode | 面试题 01.06. 字符串压缩【Pyth

    LeetCode 面试题 01.06. 字符串压缩【Easy】【Python】【双指针】 问题 力扣 字符串压缩。...

  • Java字符串压缩

    java 压缩字符串 如果源字符串长度小于64,压缩后的字符会比源字符串长。例如:str.length()=32c...

  • 2020-03-16 刷题1(字符串)

    01.06 字符串压缩 标签:字符串,内存题目其实很简单,用模拟法模拟字符串的压缩过程即可。但是我提交了三次,因为...

  • LeetCode 面试题 01.06. 字符串压缩

    题目 字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaa...

  • 面试题 01.06. 字符串压缩

    题目 字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaa...

  • 字符串压缩

    字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaaa会变...

  • 面试题 01.06. 字符串压缩

    题目:字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaa...

  • 面试题01.06_字符串压缩_hn

    题目描述 字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabccccc...

  • leetcode每日一题 python解法 3月16日

    难度:简单 题目内容: 字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串a...

网友评论

      本文标题:字符串压缩

      本文链接:https://www.haomeiwen.com/subject/vxblwktx.html