1 Star 0 Fork 332

[]~( ̄ ̄)~* / leetcode

forked from doocs / leetcode 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
README_EN.md 2.83 KB
一键复制 编辑 原始数据 按行查看 历史
ylb 提交于 2021-12-24 22:51 . style: format code and docs (#645)

01.06. Compress String

中文文档

Description

Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a - z).

Example 1:


Input: "aabcccccaaa"

Output: "a2b1c5a3"

Example 2:


Input: "abbccd"

Output: "abbccd"

Explanation: 

The compressed string is "a1b2c2d1", which is longer than the original string.

Note:

  • 0 <= S.length <= 50000

Solutions

Python3

class Solution:
    def compressString(self, S: str) -> str:
        if len(S) < 2:
            return S
        p, q = 0, 1
        res = ''
        while q < len(S):
            if S[p] != S[q]:
                res += (S[p] + str(q - p))
                p = q
            q += 1
        res += (S[p] + str(q - p))
        return res if len(res) < len(S) else S

Java

class Solution {
    public String compressString(String S) {
        int n;
        if (S == null || (n = S.length()) < 2) {
            return S;
        }
        int p = 0, q = 1;
        StringBuilder sb = new StringBuilder();
        while (q < n) {
            if (S.charAt(p) != S.charAt(q)) {
                sb.append(S.charAt(p)).append(q - p);
                p = q;
            }
            ++q;
        }
        sb.append(S.charAt(p)).append(q - p);
        String res = sb.toString();
        return res.length() < n ? res : S;
    }
}

JavaScript

/**
 * @param {string} S
 * @return {string}
 */
var compressString = function (S) {
    if (!S) return S;
    let p = 0,
        q = 1;
    let res = "";
    while (q < S.length) {
        if (S[p] != S[q]) {
            res += S[p] + (q - p);
            p = q;
        }
        ++q;
    }
    res += S[p] + (q - p);
    return res.length < S.length ? res : S;
};

Go

func compressString(S string) string {
	n := len(S)
	if n == 0 {
		return S
	}
	var builder strings.Builder
	pre, cnt := S[0], 1
	for i := 1; i < n; i++ {
		if S[i] != pre {
			builder.WriteByte(pre)
			builder.WriteString(strconv.Itoa(cnt))
			cnt = 1
		} else {
			cnt++
		}
		pre = S[i]
	}
	builder.WriteByte(pre)
	builder.WriteString(strconv.Itoa(cnt))
	if builder.Len() >= n {
		return S
	}
	return builder.String()
}

...

Java
1
https://gitee.com/keshuimao/leetcode.git
git@gitee.com:keshuimao/leetcode.git
keshuimao
leetcode
leetcode
main

搜索帮助