140.String Compression

题目:

Given an array of characters, compress it in-place.

给定一组字符,就地压缩它。

The length after compression must always be smaller than or equal to the original array.

压缩后的长度必须始终小于或等于原始数组。

Every element of the array should be a character (not int) of length 1.

数组的每个元素都应该是长度为1的字符(不是int)。

After you are done modifying the input array in-place, return the new length of the array.

在就地修改输入数组后,返回数组的新长度。


Follow up:

跟进:
Could you solve it using only O(1) extra space?

你能用O(1)额外空间解决它吗?


Example 1:

Input:
["a","a","b","b","c","c","c"]

Output:
Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]
返回6,输入数组的前6个字符应为:[“a”,“2”,“b”,“2”,“c”,“3”] Explanation: "aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3".
“aa”被“a2”取代。 “bb”被“b2”取代。 “ccc”被“c3”取代。

 

Example 2:

Input:
["a"]

Output:
Return 1, and the first 1 characters of the input array should be: ["a"]
返回1,输入数组的前1个字符应为:[“a”]
Explanation:
Nothing is replaced.

 

Example 3:

Input:
["a","b","b","b","b","b","b","b","b","b","b","b","b"]

Output:
Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].
返回4,输入数组的前4个字符应为:[“a”,“b”,“1”,“2”] Explanation: Since the character "a" does not repeat, it is not compressed. "bbbbbbbbbbbb" is replaced by "b12". Notice each digit has it's own entry in the array.
由于字符“a”不重复,因此不会压缩。 “bbbbbbbbbbbbb”被“b12”取代。
请注意,每个数字在数组中都有自己的条目。

 

Note:

  1. All characters have an ASCII value in [35, 126].
  2. 1 <= len(chars) <= 1000.

 

解答:

 1 class Solution {
 2     public int compress(char[] chars) {
 3         int slow=0,fast=0;
 4         while(fast<chars.length){
 5             char currChar=chars[fast];
 6             int count=0;
 7             while(fast<chars.length && chars[fast]==currChar){
 8                 fast++;
 9                 count++;
10             }
11             chars[slow++]=currChar;
12             if(count!=1)
13                 for(char c:Integer.toString(count).toCharArray())
14                     chars[slow++]=c;
15         }
16         return slow;
17     }
18 }

详解:

 快慢指针 滑动窗口

posted @ 2018-09-06 09:48  chan_ai_chao  阅读(80)  评论(0编辑  收藏  举报