443. String Compression

 

记录一个current char, 用j循环到没有一样的为止,要是count>1的话,就把数字放进去

 

 1 class Solution {
 2     public int compress(char[] chars) {
 3         if(chars.length == 0) return 0;
 4         if(chars.length == 1) return 1;
 5         
 6         int i = 0, j = 0;
 7         int count = 0;
 8         while(j < chars.length){
 9             char current = chars[j];
10             while(j < chars.length && chars[j] == current){
11                 count++;
12                 j++;
13             }
14             chars[i++] = current;
15             if(count != 1){
16                 String str = "" + count;
17                 char[] arr = str.toCharArray();
18                 for(char c : arr){
19                     chars[i++] = c;
20                 }       
21                 
22             }
23             
24             count = 0;
25         }
26         return i;
27         
28     }
29 }

 

posted @ 2018-10-06 13:51  jasoncool1  阅读(104)  评论(0编辑  收藏  举报