题目:利用字符重复出现的次数,可以实现基本的字符串压缩功能.字符串串“aabcccccaaa”经压缩会变成“a2b1c5a3”,若压缩后的字符串没有变短,则返回原先的字符串.
核心代码:
<pre><code>` func compressBetter(str:String) -> String {
let count:Int = str.characters.count
if count == 0 {
return ""
}
var result:String = ""
var last:Character = str[0] as Character
var charCount:Int = 0
for i in 0..<count {
let temp:Character = str[i] as Character
if temp == last {
charCount += 1
} else {
result.append(last)
result.append("\(charCount)")
last = temp
charCount = 1
}
}
result.append(last)
result.append("\(charCount)")
if result.characters.count >= count {
return str
}
return result
}`</code></pre>
测试代码:
<pre><code>var compressString:String = "abbcccdddd" var compressResult:String = myString.compressBetter(str: compressString) print("压缩结果:\(compressResult)")
</code></pre>