代码拉取完成,页面将自动刷新
同步操作将从 doocs/leetcode 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
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
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
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;
}
}
/**
* @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;
};
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()
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。