Skip to content

Commit 84c73bd

Browse files
committed
Create 面试题 01.06. 字符串压缩.js
1 parent 3866d57 commit 84c73bd

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

面试题 01.06. 字符串压缩.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
/**
2+
* @param {string} S
3+
* @return {string}
4+
*/
5+
var compressString = function(S) {
6+
let result = [];
7+
for (let i = 0; i < S.length; i++) {
8+
if (result[result.length - 1] && S[i] === result[result.length - 1][0]) {
9+
result[result.length - 1][1]++;
10+
} else {
11+
result.push([S[i], 1]);
12+
}
13+
}
14+
const str = result.map(([c, n]) => c + n).join('');
15+
return str.length < S.length ? str : S;
16+
};

0 commit comments

Comments
 (0)