Skip to content

Latest commit

 

History

History
173 lines (140 loc) · 3.48 KB

README_EN.md

File metadata and controls

173 lines (140 loc) · 3.48 KB

中文文档

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()
}

Rust

impl Solution {
    pub fn compress_string(s: String) -> String {
        let mut cs: Vec<char> = s.chars().collect();
        cs.push(' ');
        let mut res = vec![];
        let mut l = 0;
        let mut cur = cs[0];
        for i in 1..cs.len() {
            if cs[i] != cur {
                let count = (i - l).to_string();
                l = i;
                res.push(cur);
                cur = cs[i];
                for c in count.chars() {
                    res.push(c);
                }
            }
        }
        if res.len() >= cs.len() - 1 {
            s
        } else {
            res.iter().collect()
        }
    }
}

...