[Swift]LeetCode443. 壓縮字符串 | String Compression

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-ccawojqk-ew.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

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

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

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

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?微信

Example 1:app

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"]

Explanation:
"aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3".

Example 2:spa

Input:
["a"]

Output:
Return 1, and the first 1 characters of the input array should be: ["a"]

Explanation:
Nothing is replaced.

Example 3:code

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"].

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.

Note:htm

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

給定一組字符,使用原地算法將其壓縮。

壓縮後的長度必須始終小於或等於原數組長度。

數組的每一個元素應該是長度爲1 的字符(不是 int 整數類型)。

在完成原地修改輸入數組後,返回數組的新長度。

進階:
你可否僅使用O(1) 空間解決問題?

示例 1:

輸入:
["a","a","b","b","c","c","c"]

輸出:
返回6,輸入數組的前6個字符應該是:["a","2","b","2","c","3"]

說明:
"aa"被"a2"替代。"bb"被"b2"替代。"ccc"被"c3"替代。

示例 2:

輸入:
["a"]

輸出:
返回1,輸入數組的前1個字符應該是:["a"]

說明:
沒有任何字符串被替代。

示例 3:

輸入:
["a","b","b","b","b","b","b","b","b","b","b","b","b"]

輸出:
返回4,輸入數組的前4個字符應該是:["a","b","1","2"]。

說明:
因爲字符"a"不重複,因此不會被壓縮。"bbbbbbbbbbbb"被「b12」替代。
注意每一個數字在數組中都有它本身的位置。

注意:

  1. 全部字符都有一個ASCII值在[35, 126]區間內。
  2. 1 <= len(chars) <= 1000

 60ms

 1 class Solution {
 2     let intToChar : Array<Character> = ["0","1","2","3","4","5","6","7","8","9"]
 3     func compress(_ chars: inout [Character]) -> Int {
 4         if chars.count < 2 {
 5             return chars.count
 6         }
 7         var result = ""
 8         result.append(chars[0])
 9         var count = 1
10         for i in 1..<chars.count {
11             if chars[i] == chars[ i - 1]{
12                 count += 1
13             } else {
14                 if count != 1 {
15                     result += getCountStr(count)
16                 }
17                 count = 1
18                 result.append(chars[i])
19             }
20         }
21         if count > 1 {
22             result += getCountStr(count)
23         }
24          chars = Array<Character>(result)
25         return chars.count
26     }
27     private func getCountStr(_ num : Int) -> String {
28         var count = num
29         var str = ""
30         if count < 10 {
31             str.append(intToChar[count])
32         } else {
33             while count > 0 {
34                 if str.isEmpty {
35                     str.append(intToChar[count % 10])
36                 } else {
37                     str.insert(intToChar[count % 10], at: str.startIndex)
38                 }
39                 count /= 10
40             }
41         }
42         return str
43     }
44 }

92ms

 1 class Solution {
 2     func compress(_ chars: inout [Character]) -> Int {
 3         var len = 0, cnt = 1
 4         for i in 0..<chars.count {
 5             if i+1 == chars.count || chars[i] != chars[i+1] {
 6                 chars[len] = chars[i]
 7                 len += 1
 8 
 9                 if cnt > 1 {
10                     for ch in String(cnt) {
11                         chars[len] = ch
12                         len += 1
13                     }
14                     cnt = 1
15                 }
16             } else {
17                 cnt += 1
18             }
19         }
20 
21         return len
22     }
23 }

96ms

 1 class Solution {
 2     func compress(_ chars: inout [Character]) -> Int {
 3         if chars.count <= 1 {
 4             return chars.count
 5         }
 6         var nextIndex = 1
 7         var count = 1
 8         var curChar = chars[0]
 9         var i = 1
10         var l = chars.count
11         while i < l {
12             let tmpChar = chars[i]
13             if curChar == tmpChar {
14                 count += 1
15                 if i != chars.count - 1 {
16                     i += 1
17                     continue
18                 }
19             }
20             if count > 1 {
21                 let str = "\(count)"
22                 var tmplist = [Character]()
23                 for char in str {
24                     tmplist.append(char)
25                 }
26                 if i == l - 1, tmpChar == curChar {
27                    chars[nextIndex ... i] = tmplist[0 ... tmplist.count-1]
28                 }else{
29                    chars[nextIndex ... i - 1] = tmplist[0 ... tmplist.count-1]
30                 }
31                 
32                 i = nextIndex + tmplist.count + 1
33                 l = chars.count
34                 nextIndex = i
35             }else{
36                 i += 1
37             }
38             nextIndex = i
39             curChar = tmpChar
40             count = 1
41         }
42         return chars.count
43     }
44 }

104ms

 1 class Solution {
 2     func compress(_ chars: inout [Character]) -> Int {
 3         
 4         var front = 0
 5         var back = 0
 6 
 7         while back < chars.count {
 8             chars[front] = chars[back]
 9 
10             var count = 0
11             while back < chars.count, chars[back] == chars[front] {
12                 count = count + 1
13                 back = back + 1
14             }
15 
16             if count > 1 {
17                 let replacing = "\(count)".map { $0 }
18                 chars.replaceSubrange(front+1..<front+1+replacing.count, with: replacing)
19                 front = front + 1 + replacing.count
20             } else {
21                 front = front + 1
22             }
23         }
24 
25         return front        
26     }
27 }

108ms

 1 class Solution {
 2     func compress(_ chars: inout [Character]) -> Int {
 3         if chars.isEmpty { return 0 }
 4         var left = 0, count = 1, lastVal = chars[0]
 5 
 6         func helper(_ v: Character, _ c: Int) {
 7             chars[left] = v
 8             left += 1
 9             if c < 2 {
10                 return
11             }
12             let arr = Array("\(c)")
13             for t in arr {
14                 chars[left] = t
15                 left += 1
16             }
17         }
18 
19         for i in 1 ..< chars.count {
20             let char = chars[i]
21             if char == lastVal {
22                 count += 1
23             } else {
24                 helper(lastVal, count)
25                 count = 1
26                 lastVal = char
27             }
28         }
29 
30         if count > 0 {
31             helper(lastVal, count)
32         }
33 
34         return left
35     }
36 }

120ms

 1 class Solution {
 2     func compress(_ chars: inout [Character]) -> Int {
 3         guard chars.count > 1 else {
 4             return chars.count
 5         }
 6         let len = chars.count
 7         var i = 0
 8         var j = 1
 9         var count = 1
10         
11         while j < len {
12             let one = chars[i]
13             count = 1
14             while j < len &&  one == chars[j] {
15                 j += 1
16                 count += 1
17             }
18             
19             if count != 1 {
20                 let countArr = Array(String(count))
21                 for char in countArr {
22                     print(char)
23                     i += 1
24                     chars[i] = char
25                 }
26             }
27             
28             if j < len {
29                 i += 1
30                 chars[i] = chars[j]
31                 j += 1
32             }
33             
34         }
35         
36         return i + 1
37     }
38 }

156ms

 1 class Solution {
 2     func compress(_ chars: inout [Character]) -> Int {
 3         if chars.isEmpty { return 0 }
 4         var left = 0, count = 1, lastVal = chars[0]
 5 
 6         func helper(_ v: Character, _ c: Int) {
 7             chars[left] = v
 8             left += 1
 9             if c < 2 {
10                 return
11             }
12             let arr = Array("\(c)")
13             for t in arr {
14                 chars[left] = t
15                 left += 1
16             }
17         }
18 
19         for i in 1 ..< chars.count {
20             let char = chars[i]
21             if char == lastVal {
22                 count += 1
23             } else {
24                 helper(lastVal, count)
25                 count = 1
26                 lastVal = char
27             }
28         }
29 
30         if count > 0 {
31             helper(lastVal, count)
32         }
33 
34         return left
35     }
36 }

168ms

 1 class Solution {
 2     func compress(_ chars: inout [Character]) -> Int {
 3         var index = 0, currentCount = 0
 4         
 5         for i in 0..<chars.count {
 6             currentCount += 1
 7             
 8             if i + 1 == chars.count || chars[i] != chars[i + 1] {
 9                 chars[index] = chars[i]
10                 
11                 if currentCount != 1 {
12                     chars.replaceSubrange(index + 1...currentCount.length + index, with: Array(String(currentCount)))
13                 }
14                 
15                 index += currentCount == 1 ? 1 : 1 + currentCount.length
16                 currentCount = 0
17             }
18         }
19         
20         return index
21     }
22 }
23 
24 extension Int {
25     var length: Int {
26         return String(self).count
27     }
28 }
相關文章
相關標籤/搜索