-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathString_01_06.java
More file actions
52 lines (51 loc) · 1.65 KB
/
String_01_06.java
File metadata and controls
52 lines (51 loc) · 1.65 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package string;
/**
* @ProjectName: leetcode
* @Package: string
* @ClassName: String_01_06
* @Author: markey
* @Description:面试题 01.06. 字符串压缩
* 字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaaa会变为a2b1c5a3。若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)。
*
* 示例1:
*
* 输入:"aabcccccaaa"
* 输出:"a2b1c5a3"
* 示例2:
*
* 输入:"abbccd"
* 输出:"abbccd"
* 解释:"abbccd"压缩后为"a1b2c2d1",比原字符串长度更长。
* 提示:
*
* 字符串长度在[0, 50000]范围内。
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/compress-string-lcci
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
* @Date: 2020/3/16 19:27
* @Version: 1.0
*/
public class String_01_06 {
public String compressString(String S) {
if (S.length() == 0) {
return S;
}
StringBuilder sb = new StringBuilder();
char perChar = S.charAt(0);
int count = 0;
for (int i = 0; i < S.length(); i++) {
if (S.charAt(i) != perChar) {
sb.append(perChar);
sb.append(String.valueOf(count));
perChar = S.charAt(i);
count = 1;
continue;
}
count++;
}
sb.append(perChar);
sb.append(String.valueOf(count));
return S.length() == sb.length() ? S : sb.toString();
}
}