[Swift]LeetCode394. 字符串解码 | Decode String

Given an encoded string, return it‘s decoded string.

The encoding rule is: k[encoded_string], where the encoded_stringinside the square brackets is being repeated exactly k times. Note that kis guaranteed to be a positive integer.

You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.

Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won‘t be input like 3a or 2[4].

Examples:

s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".


给定一个经过编码的字符串,返回它解码后的字符串。

编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。

你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。

此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k,例如不会出现像 3a 或 2[4] 的输入。

示例:

s = "3[a]2[bc]", 返回 "aaabcbc".
s = "3[a2[c]]", 返回 "accaccacc".
s = "2[abc]3[cd]ef", 返回 "abcabccdcdcdef".

12ms
 1 class Solution {
 2     func decodeString(_ s: String) -> String {
 3         var k:Int = 0
 4         return DFS(s, &k)
 5     }
 6
 7     func DFS(_ s:String,_ k:inout Int) -> String
 8     {
 9         var ans:String = String()
10         var cnt:Int = 0
11         while(k < s.count)
12         {
13             if s[k] >= "0" && s[k] <= "9"
14             {
15                 cnt = cnt*10 + (s[k].ascii - 48)
16                 k += 1
17             }
18             else if s[k] == "["
19             {
20                 k += 1
21                 var tem:String = DFS(s, &k)
22                 for i in 0..<cnt
23                 {
24                     ans += tem
25                     cnt = 0
26                 }
27             }
28             else if s[k] == "]"
29             {
30                 k += 1
31                 return ans
32             }
33             else
34             {
35                 ans.append(s[k])
36                 k += 1
37             }
38         }
39         return ans
40     }
41 }
42
43 extension String {
44     //subscript函数可以检索数组中的值
45     //直接按照索引方式截取指定索引的字符
46     subscript (_ i: Int) -> Character {
47         //读取字符
48         get {return self[index(startIndex, offsetBy: i)]}
49     }
50 }
51
52 //Character扩展方法
53 extension Character
54 {
55   //属性:ASCII整数值(定义小写为整数值)
56    var ascii: Int {
57         get {
58             let s = String(self).unicodeScalars
59             return Int(s[s.startIndex].value)
60         }
61     }
62 }


12ms

 1 class Solution {
 2     func decodeString(_ s: String) -> String {
 3         var i = 0
 4         return String(de(Array(s),&i))
 5     }
 6
 7     let zv = "0".unicodeScalars.first!.value, nv = "9".unicodeScalars.first!.value
 8
 9     func de(_ c: [Character], _ i: inout Int) -> [Character]{
10         var num = 0
11         var ans = [Character]()
12         while i < c.count && c[i] != "]" {
13             let iv = c[i].unicodeScalars.first!.value
14             if iv<=nv && iv>=zv {
15                 num = num*10 + Int(iv-zv)
16             } else if c[i] == "[" {
17                 i+=1
18                 let re = de(c, &i)
19                 for j in  0..<num {
20                     ans += re
21                 }
22                 num=0
23
24             } else {
25                 ans.append(c[i])
26             }
27             i+=1
28         }
29         return ans
30     }
31 }


12ms

 1 import Foundation
 2 class Solution {
 3     func decodeString(_ s: String) -> String {
 4     var numOfLeft:Int = 0;
 5     var tempStack:[Character] = [Character]();
 6     var resultString:String = String();
 7
 8     func toStringWhenRight()->String{//遇到不是数字就停止
 9         var tempStr = ""
10         var tempNum = ""
11         var result = ""
12         while tempStack[tempStack.count-1] != "[" {
13             let temp = String.init(tempStack.popLast()!)
14             tempStr = temp + tempStr;
15         }
16         tempStack.removeLast()
17         while (tempStack.count>0&&tempStack[tempStack.count-1]>="0"&&tempStack[tempStack.count-1]<="9"){
18             let temp = String.init(tempStack.popLast()!)
19             tempNum = temp + tempNum;
20             // print(tempStack.count)
21         }
22         let bound = (tempNum as NSString).integerValue
23         for _ in 1...bound{
24             result += tempStr
25         }
26         //读取其余的字母
27         while (tempStack.count>0&&tempStack[tempStack.count-1]>="a"&&tempStack[tempStack.count-1]<="z"){
28             let str = String.init(tempStack.popLast()!)
29             result =  str + result;
30         }
31         numOfLeft -= 1;
32         return result
33     }
34     for char in s{
35         if(char == "["){
36             numOfLeft+=1;
37             tempStack.append(char);
38         }else if(char=="]"){
39             if(numOfLeft == 1){
40                 resultString += toStringWhenRight();
41             }else if(numOfLeft > 1){
42                 tempStack.append(contentsOf: toStringWhenRight());
43             }else{fatalError("something strange hanppens")}
44         }else{
45             tempStack.append(char);
46         }
47     }
48     resultString += String.init(tempStack);
49     return resultString;
50   }
51 }


16ms

  1 class Solution {
  2
  3     func decodeString(_ str: String) -> String {
  4         // stores the ascii values of the characters
  5         var stack: [String] = []
  6
  7         // used to store the formed number of times
  8         var number: Int? = 0
  9
 10         // running index in str
 11         var index = 0
 12         while index < str.count {
 13             let ch = str[index]
 14
 15             if ch.isNumeric() {
 16                 number = (number ?? 0) * 10 + ch.numericValue()!
 17             } else if ch == "[" {
 18                 if let number = number {
 19                     stack.append(String(number))
 20                 }
 21                 number = nil
 22                 stack.append(String(ch))
 23             } else if ch == "]" {
 24                 number = nil
 25                 // decode the string and push on to stack
 26                 var values = [String]()
 27                 var times = 0
 28                 while let top = stack.last {
 29                     if top == "[" {
 30                         // removes the square bracket
 31                         stack.removeLast()
 32
 33                         // remove the number
 34                         times = Int(stack.removeLast())!
 35
 36                         break
 37                     } else {
 38                         values.insert(stack.removeLast(), at: 0)
 39                     }
 40                 }
 41
 42                 stack.append(decodeString(times, values))
 43             } else {
 44                 number = nil
 45                 // any other character
 46                 stack.append(String(ch))
 47             }
 48
 49             index += 1
 50         }
 51
 52         let result = stack.reduce("") { $0 + $1 }
 53         return result
 54     }
 55
 56     func decodeString(_ times: Int, _ values: [String]) -> String {
 57         let str = values.reduce("", +)
 58         var result = ""
 59         for _ in 0..<times {
 60             result += str
 61         }
 62
 63         return result
 64     }
 65
 66 }
 67
 68 extension String {
 69
 70     subscript (i: Int) -> Character {
 71         return self[index(startIndex, offsetBy: i)]
 72     }
 73
 74     func subString(from: Int, to: Int) -> String {
 75         guard from <= to else {
 76             return ""
 77         }
 78
 79         let startIndex = self.index(self.startIndex, offsetBy: from)
 80         let endIndex = self.index(self.startIndex, offsetBy: to)
 81         return String(self[startIndex...endIndex])
 82     }
 83
 84     func subString(from: Int) -> String {
 85         let startIndex = self.index(self.startIndex, offsetBy: from)
 86         return String(self.suffix(from: startIndex))
 87     }
 88
 89     func asciiValues() -> [Int] {
 90         return Array(self.utf16).map { Int($0) }
 91     }
 92
 93     mutating func lTrim() {
 94         if let trailingSpacesRange = self.range(of: "^\\s+", options: .regularExpression) {
 95             self.replaceSubrange(trailingSpacesRange, with: "")
 96         }
 97     }
 98
 99     mutating func rTrim() {
100         if let trailingSpacesRange = self.range(of: "\\s+$", options: .regularExpression) {
101             self.replaceSubrange(trailingSpacesRange, with: "")
102         }
103     }
104
105 }
106
107 struct AsciiValue {
108     static let zero = Int(Character("0").unicodeScalars.first?.value ?? 0)
109     static let nine = Int(Character("9").unicodeScalars.first?.value ?? 0)
110     static let lowercaseCaseA = Int(Character("a").unicodeScalars.first?.value ?? 0)
111     static let lowercaseCaseZ = Int(Character("z").unicodeScalars.first?.value ?? 0)
112     static let capitalCaseA = Int(Character("A").unicodeScalars.first?.value ?? 0)
113     static let capitalCaseZ = Int(Character("Z").unicodeScalars.first?.value ?? 0)
114     static let openBracket = Int(Character("(").unicodeScalars.first?.value ?? 0)
115     static let closeBracket = Int(Character(")").unicodeScalars.first?.value ?? 0)
116     static let openSquareBracket = Int(Character("[").unicodeScalars.first?.value ?? 0)
117     static let closeSquareBracket = Int(Character("]").unicodeScalars.first?.value ?? 0)
118     static let openCurlyBracket = Int(Character("{").unicodeScalars.first?.value ?? 0)
119     static let closeCurlyBracket = Int(Character("}").unicodeScalars.first?.value ?? 0)
120     static let exponent = Int(Character("e").unicodeScalars.first?.value ?? 0)
121     static let plus = Int(Character("+").unicodeScalars.first?.value ?? 0)
122     static let minus = Int(Character("-").unicodeScalars.first?.value ?? 0)
123     static let star = Int(Character("*").unicodeScalars.first?.value ?? 0)
124     static let forwardSlash = Int(Character("/").unicodeScalars.first?.value ?? 0)
125     static let decimal = Int(Character(".").unicodeScalars.first?.value ?? 0)
126 }
127
128 extension Character {
129
130     func isAlpha() -> Bool {
131         switch self {
132         case "a"..."z":
133             return true
134         case "A"..."Z":
135             return true
136         default:
137             return false
138         }
139     }
140
141     func isHexaAlpha() -> Bool {
142         switch self {
143         case "a"..."f":
144             return true
145         case "A"..."F":
146             return true
147         default:
148             return false
149         }
150     }
151
152     func isNumeric() -> Bool {
153         switch self {
154         case "0"..."9":
155             return true
156         default:
157             return false
158         }
159     }
160
161     func isAlphaNumeric() -> Bool {
162         return isAlpha() || isNumeric()
163     }
164
165     func numericValue() -> Int? {
166         guard let unicodeScalar = unicodeScalars.first else {
167             return nil
168         }
169         return Int(unicodeScalar.value) - AsciiValue.zero
170     }
171
172     var asciiValue: Int {
173         return Int(self.unicodeScalars.first!.value)
174     }
175 }


20ms

 1 class Solution {
 2     func decodeString(_ s: String) -> String {
 3         var strArr = [String]()
 4         var numIndex = 0
 5
 6         for i in 0..<s.count {
 7             var strItmeIndex = s.index(s.endIndex, offsetBy: -(i + 1))
 8             var strItme = String.init(s[strItmeIndex])
 9             if strItme != "["{
10
11                 if self.isPurnInt(string: strItme){
12                     var numStr:String = strItme
13
14                     while  self.isPurnInt(string: strArr.last!){
15                         numStr =  numStr + strArr.last!
16                         strArr.remove(at: strArr.count - 1)
17                     }
18                     if i != s.count - 1{
19                         strArr.append(numStr)
20                     }else{
21                         var strItmeInt:Int = Int(numStr)!
22                         var strNew:String = ""
23                         for j in 0..<strItmeInt{
24                             strNew = strNew + strArr.last!;
25                         }
26                         strArr.remove(at: strArr.count - 1)
27                         strArr.append(strNew)
28                     }
29
30
31                 }else{
32                     if strArr.count > 0 && self.isPurnInt(string: strArr.last!) {
33                         var strItmeInt:Int = Int(strArr.last!)!
34                         strArr.remove(at: strArr.count - 1)
35                         var strNew:String = ""
36                         for j in 0..<strItmeInt{
37                             strNew = strNew + strArr.last!;
38                         }
39                       strArr.remove(at: strArr.count - 1)
40                       strArr.append(strNew)
41                     }
42                     strArr.append(strItme)
43                 }
44             }else{
45
46                 var strNew:String = ""
47
48                 if strArr.count > 0 && self.isPurnInt(string: strArr.last!) {
49                     var strItmeInt:Int = Int(strArr.last!)!
50                     strArr.remove(at: strArr.count - 1)
51                     for j in 0..<strItmeInt{
52                         strNew = strNew + strArr.last!;
53                     }
54                     strArr.remove(at: strArr.count - 1)
55                     strArr.append(strNew)
56                 }
57                 strNew = ""
58
59                 while strArr.last != "]"{
60                     strNew = strNew + strArr.last!;
61                     strArr.remove(at: strArr.count - 1)
62                 }
63                 strArr.remove(at: strArr.count - 1)
64                 strArr.append(strNew)
65             }
66         }
67         var result:String = ""
68         for k in 0..<strArr.count{
69             result =  strArr[k] + result
70         }
71
72         return result
73     }
74
75     func isPurnInt(string: String) -> Bool {
76         let scan: Scanner = Scanner(string: string)
77         var val:Int = 0
78         return scan.scanInt(&val) && scan.isAtEnd
79     }
80 }


20ms

 1 class Solution {
 2     func decodeString(_ s: String) -> String {
 3         var nums = [Int]()
 4         var words = [String]()
 5         let chars = Array(s)
 6         var curNum = 0
 7         var result = ""
 8
 9         for char in s {
10             if char == "[" {
11                 nums.append(curNum)
12                 words.append("")
13                 curNum = 0
14             } else if char == "]" {
15                 var wordToAdd = String(repeating: words.popLast()!, count: nums.popLast()!)
16                 if words.count > nums.count {
17                     wordToAdd = words.popLast()! + wordToAdd
18                 }
19
20                 if let prevWord = words.popLast() {
21                     words.append(prevWord + wordToAdd)
22                 } else {
23                     result.append(contentsOf: wordToAdd)
24                 }
25             } else if let num = Int(String(char)) {
26                 curNum = curNum * 10 + num
27             } else {
28                 if nums.count == 0 {
29                     result.append(char)
30                 } else {
31                     let prevWord = words.popLast() ?? ""
32                     words.append(prevWord + String(char))
33                 }
34             }
35         }
36         return result
37     }
38 }

原文地址:https://www.cnblogs.com/strengthen/p/10300572.html

时间: 2024-11-06 07:50:53

[Swift]LeetCode394. 字符串解码 | Decode String的相关文章

Swift学习—字符串&amp;数组&amp;字典

字符串 OC和Swift中字符串的区别 在OC中字符串类型时NSString,在Swift中字符串类型是String OC中字符串@"",Swift中字符串"" Swift中String是第一个结构体,性能更高 String支持直接遍历 Swift提供了String和NSString之间的无缝转换 字符串的使用 用反斜线 \ 和小括号 () 做字符串插值(把常量\变量插入到字符串中) let hand = 2var age1 = 20let string1 = &q

Swift之字符串(String)

学习一门新语言怎么能少的了字符串呢.Swift中的String和Objective-C语言中NSString还是区别不小的,Swift中的String又回归了正常状态,使用起来更为方便快捷.本篇博客的主题就是Swift中的字符串类型String,String在Swift中让人省心了不少.今天这篇博客就好好的认识一下Swift中的String. 一.字符串拷贝 在Swift中的字符串拷贝直接可以使用=号来操作,这个等号不是指针之间的赋值这么简单.如果将字符串A的值赋给字符串B,那么A和B的的内存地

窥探Swift之字符串(String)

之前总结过Objective-C中的字符串<Objective-C精选字符串处理方法>,学习一门新语言怎么能少的了字符串呢.Swift中的String和Objective-C语言中NSString还是区别不小的,Swift中的String又回归了正常状态,使用起来更为方便快捷.本篇博客的主题就是Swift中的字符串类型String,String在Swift中让人省心了不少.今天这篇博客就好好的认识一下Swift中的String. 一.字符串拷贝 在Swift中的字符串拷贝直接可以使用=号来操作

浅谈swift的字符串的常用方法

下面呢, 我们就列举一些常用的swift的字符串的方法 首先呢, 我们先定义一些字符串的变量和常量 var welcome = "hello world" //值为hello you var string = "hai" let ch: Character = "!" 字符串的连接,其实的话, 字符串的连接的话, 直接用var i:String = "abc" + "def",就可以搞定,居然我们说到字符串

Swift入门(九)——String与Int、Double、Float等数字相互转换

三种转换模式 任何语言里面,Int.float.double等数字类型自成一派,但它们和String类型之间的转换总是不太方便,这里总结一下它们相互转换的方法.总结下来一共有三种转换模式,分别举例说明. 一.String转数字 这里以String类型转Int类型为例.String转其他的数字类型(Float.Double等)大同小异.主要用到的方法是String类型的toInt方法.注意这个方法返回的是Int?,即一个整数可选类型.所以需要解封. var string = "1234"

python json形式的字符串 解码还原为json

1 #coding:utf8 2 import demjson 3 '''这个方法可以很方便的把dict,list等json格式的数据 4 编码成字符串 5 和把字符串解码还原为json 6 7 注意点:就是字符串是json形式的,但是类型是字符串 8 ''' 9 data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ] 10 json = demjson.encode(data) 11 data2 = demjson.decode(j

Swift 常用字符串操作

原文链接:http://www.jianshu.com/p/52e7580166ff 版本2:增加了Swift 2.0的语法,与Swift 1.2的语法相比,主要是:advance方法变成了advancedBy方法(但不是简单替换):没有了count方法,count(str)需要变成str.characters.count等. 字符串的定义 var str1="hello, mandarava." //字符串变量 let str2="hello, mandarava.&quo

swift中字符串截取方法(substring)

下面介绍2种swift的字符串截取方法,实际上用到了substringFromIndex,substringToIndex,substringWithRange 1.将String转化为NSString再截取,代码如下:  var s="1234567890"var ns1=(s as NSString).substringFromIndex(5)var ns2=(s as NSString).substringToIndex(4)var ns3=(s as NSString).sub

C风格字符串和C++ string 对象赋值操作的性能比较

<<C++ Primer>> 第四版 Exercise Section 4.3.1 部分Exercise 4.2.9 习题如下: 在自己本机执行如下程序,记录程序执行时间: 1 #include "stdafx.h" 2 #include <iostream> 3 #include <string> 4 #include <vector> 5 #include <ctime> 6 7 using namespace