Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

面试题 01.06. 字符串压缩 #23

Open
yankewei opened this issue Mar 15, 2020 · 0 comments
Open

面试题 01.06. 字符串压缩 #23

yankewei opened this issue Mar 15, 2020 · 0 comments
Labels
字符串 题目类型为字符串 简单 题目难度为简单

Comments

@yankewei
Copy link
Owner

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

示例1:

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

示例2:

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

提示:

字符串长度在[0, 50000]范围内。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/compress-string-lcci

解答

没有什么可说的,水题

func compressString(S string) string {
    var t strings.Builder
    var cnt int
    var end byte
    for i := 0; i < len(S); i++ {
	lenT := t.Len()
	if lenT == 0 { // t为空
	    t.WriteByte(S[i])
	    end = S[i]
	    cnt = 1
	} else {
	    if S[i] == end { // t的最后一个字符和当前遍历的字符一样
		cnt++
	    } else {
		t.WriteString(strconv.Itoa(cnt))
		end = S[i]
		t.WriteByte(end)
		cnt = 1
	    }
	}
    }
    t.WriteString(strconv.Itoa(cnt))
    if len(S) > t.Len() {
	return t.String()
    }
    return S
}
@yankewei yankewei added 简单 题目难度为简单 字符串 题目类型为字符串 labels Mar 15, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
字符串 题目类型为字符串 简单 题目难度为简单
Projects
None yet
Development

No branches or pull requests

1 participant