# 字符串压缩

# 难度:简单

# 描述:

设计一种方法,通过给重复字符计数来进行基本的字符串压缩。

例如,字符串 aabcccccaaa 可压缩为 a2b1c5a3 。而如果压缩后的字符数不小于原始的字符数,则返回原始的字符串。

可以假设字符串仅包括 a-z 的字母。

# 样例:

str=aabcccccaaa 返回 a2b1c5a3

str=aabbcc 返回 aabbcc

str=aaaa 返回 a4

# 思路分析:

解题思路:取出字符串,判断重复停止,添加到新字符串中。

注:需判断压缩后的字符串长度和原始字符串长度。

# 代码模板:

const compress = function(originalString) {}
1

# 想一想再看答案

# 想一想再看答案

# 想一想再看答案

# 代码:

// 取出字符串,判断重复停止,添加到新字符串中
const compress = function(originalString) {
	if (originalString.length <= 1) return originalString // 直接返回源字符串
	let newStr = ''
	let s = originalString.charAt(0)
	let num = 1 // 跳过第一个
	let total = originalString.length
	for (let i = 1; i < total; i++) {
		let nowS = originalString.charAt(i)
		if (nowS === s) {
			num = num + 1 // 增加数量
			if (i + 1 === total) {
				newStr += `${s}${num}` // 遍历结束时,拼接最后的字符串
			}
		} else {
			newStr += `${s}${num}` // 拼接字符串
			num = 1 // 重置为1
			s = nowS // 转为下一个字符s
		}
	}
	// 生成的字符串长度大于等于源字符串 返回源字符串 否则返回生成的字符串
	if (newStr.length >= originalString.length) {
		return originalString
	} else {
		return newStr
	}
}
console.log(
	'输出:',
	compress('aabcccccaaa'), // a2b1c5a3
	compress('aabbcc'), // aabbcc
	compress('aaaa'), // a4
	compress('a'), // a
	compress('') // ''
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

# 点个Star支持我一下~