Given a set of characters, using in-place algorithm to compress.
Length after compression must always be less than or equal to the length of the original array.
Each element of the array should be a length of 1 character (not integer type int).
After completion of the in situ modification of the input array, returns the new length of the array.
Example 1:
输入:
["a","a","b","b","c","c","c"]
Output:
Returns 6, the first six characters of the input array should be: [ "a", "2 ", "b", "2", "c", "3"]
Description:
"AA" is "a2" instead. "bb" is replaced by "b2". "ccc" is replaced by "c3".
Example 2:
Input:
[ "A"]
Output:
Returns 1, a character input before the array should be: [ "a"]
Description:
No character string is replaced.
solution:
func compress(_ chars: inout [Character]) -> Int {
let count:Int = chars.count
guard count > 0 else {
return 0
}
var result:String = ""
var first:Character = chars[0] as Character
var charCount:Int = 0
for i in 0..<count {
let temp:Character = chars[i] as Character
if temp == first {
charCount += 1
} else {
result.append(first)
if charCount > 1 {
result.append("\(charCount)")
}
first = temp
charCount = 1
}
}
result.append(first)
if charCount > 1 {
result.append("\(charCount)")
}
return result.count
}