[Swift]LeetCode387. 字符串中的第一個惟一字符 | First Unique Character in a String

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-wkzlqttz-w.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.git

Examples:github

s = "leetcode"
return 0.

s = "loveleetcode",
return 2.

 

Note: You may assume the string contain only lowercase letters.數組

給定一個字符串,找到它的第一個不重複的字符,並返回它的索引。若是不存在,則返回 -1。微信

案例:spa

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.

 

注意事項:您能夠假定該字符串只包含小寫字母。code


 1 class Solution {
 2     func firstUniqChar(_ s: String) -> Int {
 3        //把英文字符都存入數組中
 4         var arr = Array<Int>(repeating: 0, count: 26)
 5         for asc in s.unicodeScalars
 6         {
 7             let num:Int = Int(asc.value - 97)
 8             //記錄字符出現的次數
 9             arr[num] += 1
10         }
11         //再次循環字符串,使用enumerated()獲取到字符串的索引
12         for (index, asc) in s.unicodeScalars.enumerated()
13         {
14             let count = arr[Int(asc.value - 97)]
15             if count == 1 {
16                 return index
17             }
18         }
19         return -1
20     }
21 }

104mshtm

 1 class Solution {
 2     func firstUniqChar(_ s: String) -> Int {
 3         var list:[Int] = [Int](repeating: 0, count: 26)
 4         for charCode in s.unicodeScalars {
 5             let tempIndex:Int = Int(charCode.value) - 97
 6             list[tempIndex] += 1
 7         }
 8         
 9         var index = 0
10         for charCode in s.unicodeScalars {
11             let tempIndex:Int = Int(charCode.value) - 97
12             if list[tempIndex] == 1 {
13                 return index
14             }
15             index += 1
16         }
17         return -1
18     }
19 }

128msblog

 1 class Solution {
 2   func firstUniqChar(_ s: String) -> Int {
 3       var countFor = Array(repeating:0, count:26)
 4       let offset = 97
 5       for charCode in s.utf8 {
 6           let adjustedCharCode = Int(charCode) - offset
 7           countFor[adjustedCharCode] += 1
 8       }
 9       for (i, charCode) in s.utf8.enumerated() {
10           let adjustedCharCode = Int(charCode) - offset
11           if countFor[adjustedCharCode] == 1 {
12               return i
13           }
14       }
15       return -1
16   }
17 }
相關文章
相關標籤/搜索