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

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

比如,字符串aabcccccaaa会变为a2b1c5a3。若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)。

 示例1:

 输入:"aabcccccaaa"
 输出:"a2b1c5a3"


 示例2:

 输入:"abbccd"
 输出:"abbccd"
 解释:"abbccd"压缩后为"a1b2c2d1",比原字符串长度更长。

提示:

字符串长度在[0, 50000]范围内。
链接:https://leetcode-cn.com/problems/compress-string-lcci

双指针

c++

string compressString(string S) {
    int N = S.length();
    string res;
    int i = 0;
    while (i < N) {
        int j = i;
        while (j < N && S[j] == S[i]) {
            j++;
        }
        res += S[i];
        res += to_string(j - i);
        i = j;
    }

    if (res.length() < S.length()) {
        return res;
    } else {
        return S;
    }
}

java

class Solution {
    public String compressString(String S) {
        if(S.length() == 0)
            return "";
        StringBuilder sb = new StringBuilder();
        char[] chars = S.toCharArray();
        int index = 0;
        int count = 0;
        for(int i = 0; i < chars.length-1; i++)
        {
            count++;
            if(chars[i] != chars[i+1])
            {
                sb.append(chars[i]).append(count);
                count = 0;
                index = i+1;
            }
        }
        sb.append(chars[index]).append(chars.length - index);
        String result = sb.toString();

       return  result.length() < S.length() ? result : S;
    }
}

python

def compressString(self, S: str) -> str:
    N = len(S)
    res = ''
    i = 0
    while i < N:
        j = i
        while j < N and S[j] == S[i]:
            j += 1
        res += S[i] + str(j - i)
        i = j

    if len(res) < len(S):
        return res
    else:
        return S

猜你喜欢

转载自www.cnblogs.com/wwj99/p/12501896.html