[Swift]LeetCode917. 仅仅反转字母 | Reverse Only Letters

Given a string S, return the "reversed" string where all characters that are not a letter stay in the same place, and all letters reverse their positions.

 

Example 1:

Input: "ab-cd"
Output: "dc-ba"

Example 2:

Input: "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"

Example 3:

Input: "Test1ng-Leet=code-Q!"
Output: "Qedo1ct-eeLg=ntse-T!"

给定一个字符串 S,返回 “反转后的” 字符串,其中不是字母的字符都保留在原地,而所有字母的位置发生反转。

示例 1:

输入:"ab-cd"
输出:"dc-ba"

示例 2:

输入:"a-bC-dEf-ghIj"
输出:"j-Ih-gfE-dCba"

示例 3:

输入:"Test1ng-Leet=code-Q!"
输出:"Qedo1ct-eeLg=ntse-T!"

40ms
 1 class Solution {
 2     func reverseOnlyLetters(_ S: String) -> String {
 3         //空字符串情况
 4         guard S != nil else {
 5             return S
 6         }
 7         //创建字典记录非字母
 8         var chars:[Int:Character] = [Int:Character]()
 9         //存储顺序字母
10         var temp:String = String()
11         //按索引遍历字符串
12         for i in 0..<S.count
13         {
14             //获取字符
15             let letter:Character = S[S.index(S.startIndex, offsetBy: i)]
16             //判断字母
17             if checkLetter(letter)
18             {
19                 //存储字母
20                 temp.append(letter)
21             }
22             else
23             {
24                 //记录非字母
25                 chars[i] = letter
26             }
27         }
28         //字符串整体反转
29         var result:String = String(temp.reversed())
30         //创建等长度字符串数组
31         var resultArray = Array(repeating:"", count: S.count)
32         //判断记录是否为空
33         if chars.isEmpty
34         {
35             return result
36         }
37         else
38         {
39             //遍历非字母
40             for key in chars.keys
41             {
42                 //填入非字母
43                 resultArray[key] = String(chars[key]!)
44             }
45             //遍历逆序字母
46             for char in result
47             {
48                 //遍历数组
49                 for j in 0..<resultArray.count
50                 {
51                     //判断是否包含非字母
52                     if String(resultArray[j]) == ""
53                     {
54                         //将逆序字母依次填入数组
55                         resultArray[j] = String(char)
56                         break
57                     }
58                 }
59             }
60             //将数组转化为字符串
61             result  = resultArray.joined(separator: "")
62         }
63         return result
64     }
65     //判断字母
66     func checkLetter(_ char:Character)->Bool
67     {
68         var num:UInt32 = UInt32()
69         for asc in char.unicodeScalars
70         {
71             num = asc.value
72         }
73         //65~90:A-Z
74         //97~122:a-z
75         if (num > 64 && num < 91) || (num > 96 && num < 123)
76         {
77             return true
78         }
79         else
80         {
81             return false
82         }
83     }
84 }

猜你喜欢

转载自www.cnblogs.com/strengthen/p/9750841.html