ios - 返回多个字符串字符

标签 ios swift

我想创建一个函数,输入一个字符串,输出返回一个表示该数字重复次数的字符串。例如,如果我的字符串是“1111223444”,它将返回“41221334”,因为有四个 1、两个 2、一个 3 和三个 4。因此输入“2234467”将返回“2213241617”。我不确定字典是否是实现它的最佳方式,我真的很困惑。我已经启动了该功能,但不知道从这里去哪里。任何提示或资源都会有所帮助。

     func stringOutput(input: String) -> String {

         var result = ""
         var lastCharacter: Character
         var count = 0
         var countDict: [String: Int] = [:]

         for item in input {
          countDict[item] as Character

             }

      return result
             }

最佳答案

您的函数计算 Look-and-say sequence 的下一项.这是一个实现(基本上取自代码审查中的 Leetcode 38: The “count-and-say” sequence)。我们不遍历字符串,而是直接搜索与当前字符不同的字符的下一个索引。第一次和最后一次运行都没有被特殊对待:

extension String {

    func lookAndSay() -> String {
        var result = ""
        var fromIndex = startIndex // Start of current run
        while fromIndex != endIndex {
            let char = self[fromIndex] // Current character
            // Find start of next run
            let toIndex = self[fromIndex...].firstIndex(where: { $0 != char }) ?? endIndex
            // Compute length of run, and append it to the result
            let len = distance(from: fromIndex, to: toIndex)
            result += "\(len)\(char)"
            // Continue with next run
            fromIndex = toIndex
        }
        return result
    }
}

print("1111223444".lookAndSay()) // 41221334
print("2234467".lookAndSay()) // 2213241617

关于ios - 返回多个字符串字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59186917/

相关文章:

ios - 如何设置应用程序以从 url iOS 接收 utm 参数?

ios - 切换到其他页面时取消选择选定的单元格

iOS 根据字符数动态标签宽度

swift - 字典序列的扩展,其中值是 Equatable

ios - NSUserDefaults 似乎没有创建全局可访问的变量

ios - 创建一个类似于 FB 和 Gmail iPhone 应用程序的隐藏菜单,单击按钮时,页面滑动一半以显示菜单

ios - 以编程方式检测 iOS 中的蜂窝网络类型

ios - 如何在 objective-C 中设置标签栏标题的字体

c# - 如何创建一个项目来为支持 iOS、Android 和 UWP 的 Xamarin Forms 创建 Nuget 包?

ios - 将对 viewController 的引用传递给其他 viewController cocoa touch