File tree Expand file tree Collapse file tree
src/main/java/com/algorithm/study/demo/algorithm/leetcode Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .algorithm .study .demo .algorithm .leetcode ;
2+
3+ /**
4+ * @author xun2.liu
5+ * @title: Solution22
6+ * @projectName algorithm-study
7+ * @description: 字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。
8+ * 比如,字符串aabcccccaaa会变为a2b1c5a3。若“压缩”后的字符串没有变短,则返回原先的字符串。
9+ * 你可以假设字符串中只包含大小写英文字母(a至z)。
10+ * 示例1:
11+ *
12+ * 输入:"aabcccccaaa"
13+ * 输出:"a2b1c5a3"
14+ *
15+ * 来源:力扣(LeetCode)
16+ * 链接:https://leetcode-cn.com/problems/compress-string-lcci
17+ * @date 2020/6/3 20:07
18+ */
19+ public class Solution22 {
20+ public static String compressString (String S ) {
21+ //慢指针
22+ int i =0 ;
23+ int len =S .length ();
24+ //压缩后的字符串
25+ StringBuilder sb =new StringBuilder ();
26+ while (i <len ){
27+ //快指针
28+ int j =i ;
29+ //j<len防止越界,判断快慢指针对应的字符是否一致。如果一致的话快指正继续往前走。
30+ while (j <len && S .charAt (i )==S .charAt (j )){
31+ j ++;
32+ }
33+ sb .append (S .charAt (i )).append (j -i );
34+ //最后调整慢指针跟快指针对齐
35+ i =j ;
36+ }
37+ if (sb .length ()<S .length ()){
38+ return sb .toString ();
39+ }
40+ return S ;
41+ }
42+
43+ public static void main (String [] args ) {
44+ System .out .println (compressString ("aabcccccaaa" ));
45+ }
46+ }
You can’t perform that action at this time.
0 commit comments