140.String Compression
生活随笔
收集整理的這篇文章主要介紹了
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 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 }詳解:
?快慢指針 滑動窗口
轉載于:https://www.cnblogs.com/chanaichao/p/9594488.html
總結
以上是生活随笔為你收集整理的140.String Compression的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python 中的 if __name_
- 下一篇: 【WinForm-无边框窗体】实现Pan