日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

140.String Compression

發布時間:2023/12/18 编程问答 45 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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:

  • All characters have an ASCII value in?[35, 126].
  • 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 }

    詳解:

    ?快慢指針 滑動窗口

    轉載于:https://www.cnblogs.com/chanaichao/p/9594488.html

    總結

    以上是生活随笔為你收集整理的140.String Compression的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。