1. 程式人生 > >[Swift]LeetCode291. 詞語模式之二 $ Word Pattern II

[Swift]LeetCode291. 詞語模式之二 $ Word Pattern II

class NPU () only ret max 字符串 substr offset

Given a pattern and a string str, find if strfollows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty substring in str.

Example 1:

Input: pattern = "abab", str = "redblueredblue"
Output: true

Example 2:

Input: pattern = "aaaa"
, str = "asdasdasdasd" Output: false

Example 3:

Input: pattern = "aabb", str = "xyzabcxzyabc"
Output: false

Notes:
  You may assume both pattern and str contains only lowercase letters.


給定一個模式和一個字符串str,找出str是否遵循相同的模式。

這裏follow意味著完全匹配,這樣在模式中的字母和str中的非空子字符串之間就有一個雙射。

例1:

  輸入:pattern=“abab”,str=“redblueredblue”

  輸出:true

例2:

  輸入:pattern=“aaaa”,str=“asdasdasd”

  輸出:false

例3:

  輸入:pattern=“aabb”,str=“xyzabcxzyabc”

  輸出:false

註意:

  您可以假定pattern和str都只包含小寫字母。


Solution:

 1 class Solution {
 2     var m:[Character:String] = [Character:String]()
 3
var s:Set<String> = Set<String>() 4 func wordPatternMatch(_ pattern:String,_ str:String) -> Bool { 5 if pattern.isEmpty {return str.isEmpty} 6 var arrChar:[Character] = Array( pattern) 7 if m[arrChar[0]] != nil 8 { 9 var t:String = m[arrChar[0]]! 10 if t.count > str.count || str.subString(0, t.count) != t 11 { 12 return false 13 } 14 if wordPatternMatch(pattern.subString(1), str.subString(t.count)) 15 { 16 return true 17 } 18 } 19 else 20 { 21 for i in 1...str.count 22 { 23 if s.contains(str.subString(0, i)) {continue} 24 m[arrChar[0]] = str.subString(0, i) 25 s.insert(str.subString(0, i)) 26 if wordPatternMatch(pattern.subString(1), str.subString(i)) 27 { 28 return true 29 } 30 m[arrChar[0]] = nil 31 s.remove(str.subString(0, i)) 32 } 33 } 34 return false 35 } 36 } 37 38 extension String { 39 // 截取字符串:從index到結束處 40 // - Parameter index: 開始索引 41 // - Returns: 子字符串 42 func subString(_ index: Int) -> String { 43 let theIndex = self.index(self.endIndex, offsetBy: index - self.count) 44 return String(self[theIndex..<endIndex]) 45 } 46 47 // 截取字符串:指定索引和字符數 48 // - begin: 開始截取處索引 49 // - count: 截取的字符數量 50 func subString(_ begin:Int,_ count:Int) -> String { 51 let start = self.index(self.startIndex, offsetBy: max(0, begin)) 52 let end = self.index(self.startIndex, offsetBy: min(self.count, begin + count)) 53 return String(self[start..<end]) 54 } 55 }

點擊:Playground測試

1 var sol = Solution()
2 print(sol.wordPatternMatch("abab","redblueredblue"))
3 //Print true
4 print(sol.wordPatternMatch("aaaa","asdasdasdasd"))
5 //Print false
6 print(sol.wordPatternMatch("aabb","xyzabcxzyabc"))
7 //Print false

[Swift]LeetCode291. 詞語模式之二 $ Word Pattern II