题目:给定一个字符串,计算出从做到右的字符出现的个数
忽略字符计算后个数为1的数字
例如
原始输入字符串:"aabccccaaa
"
期望输出: “a2bc4a3
”
解释:
从左到右,
- a出现了2次,记为a2;
- b出现了1次,记为b;
- c出现了4次,记为c4;
- 再a出现了3次,记为a3。
- 结果就是:
a2bc4a3
以Swift语言实现如下
class TestA: NSObject {
private var lowerLetters: [String: Int] = ["a":0, "b":0, "c":0, "d":0, "e":0, "f":0, "g":0, "h":0, "i":0, "j":0, "k":0, "l":0, "m":0, "n":0, "o":0, "p":0, "q":0, "r":0, "s":0, "t":0, "u":0, "v":0, "w":0, "x":0, "y":0, "z":0]
override init() {
super.init()
// 1.输入
let s1 = "aabccccaaa"
let s2 = "a2bc4a3"
// 2.计算
let result = self.calculate(with: s1)
// 3.测试
print("原始字符串 s1: \(s1)")
print("原始期望结果 s2: \(s2)")
print("计算后字符串 result: \(result)")
if result == s2 {
print("测试通过!")
}
}
// 计算字符的个数
private func calculate(with plainText: String) -> String {
var finalStr: String = ""
var lastCharacter: String = ""
var currentIndex: Int = 0
for c in plainText {
if lastCharacter == String(c) {
// 如果字符相等,继续加1
let cCount: Int = lowerLetters[String(c)] ?? 0
lowerLetters[String(c)] = cCount + 1
if currentIndex == plainText.count - 1 {
// 如果是字符串的最后一个字符,则直接计算
finalStr += self.combineNumberOfOcurrencesCharacters(withLastCharacter: lastCharacter)
}
} else {
// 如果不相等,就累计上一次字符的计算个数
finalStr += self.combineNumberOfOcurrencesCharacters(withLastCharacter: lastCharacter)
// 再把上一个字符置为0,否则后续出现的字符数量不对
lowerLetters[lastCharacter] = 0
// 计算当前字符的个数
let cCount: Int = lowerLetters[String(c)] ?? 0
lowerLetters[String(c)] = cCount + 1
}
currentIndex += 1
lastCharacter = String(c)
}
return finalStr
}
// 组合字符出现的次数
private func combineNumberOfOcurrencesCharacters(withLastCharacter lastCharacter: String) -> String {
let lastLetterCount: Int = lowerLetters[lastCharacter] ?? 0
if lastLetterCount > 1 {
return "\(lastCharacter)\(lastLetterCount)"
} else {
return "\(lastCharacter)"
}
}
}
输出测试结果如图
// 1.输入
let s1 = "aabccccaaa"
let s2 = "a2bc4a3"
// 2.计算
let result = self.calculate(with: s1)
// 3.测试
print("原始字符串 s1: \(s1)")
print("原始期望结果 s2: \(s2)")
print("计算后字符串 result: \(result)")
if result == s2 {
print("测试通过!")
}