★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:为敢(WeiGanTechnologies)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-gnrjqvum-kp.html
➤若是连接不是山青咏芝的博客园地址,则多是爬取做者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持做者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given two strings str1
and str2
of the same length, determine whether you can transform str1
into str2
by doing zero or more conversions.git
In one conversion you can convert all occurrences of one character in str1
to any other lowercase English character.github
Return true
if and only if you can transform str1
into str2
.微信
Example 1:spa
Input: str1 = "aabcc", str2 = "ccdee" Output: true Explanation: Convert 'c' to 'e' then 'b' to 'd' then 'a' to 'c'. Note that the order of conversions matter.
Example 2:code
Input: str1 = "leetcode", str2 = "codeleet" Output: false Explanation: There is no way to transform str1 to str2.
Note:orm
1 <= str1.length == str2.length <= 10^4
str1
and str2
contain only lowercase English letters.给出两个长度相同的字符串,分别是 str1
和 str2
。请你帮忙判断字符串 str1
能不能在 零次 或 屡次 转化后变成字符串 str2
。htm
每一次转化时,将会一次性将 str1
中出现的 全部 相同字母变成其余 任何 小写英文字母(见示例)。blog
只有在字符串 str1
可以经过上述方式顺利转化为字符串 str2
时才能返回 True
,不然返回 False
。ci
示例 1:
输入:str1 = "aabcc", str2 = "ccdee" 输出:true 解释:将 'c' 变成 'e',而后把 'b' 变成 'd',接着再把 'a' 变成 'c'。注意,转化的顺序也很重要。
示例 2:
输入:str1 = "leetcode", str2 = "codeleet" 输出:false 解释:咱们没有办法可以把 str1 转化为 str2。
提示:
1 <= str1.length == str2.length <= 10^4
str1
和 str2
中都只会出现 小写英文字母72ms
1 class Solution { 2 func canConvert(_ str1: String, _ str2: String) -> Bool { 3 if str1 == str2 {return true} 4 let n:Int = str1.count 5 var arr:[Int] = [Int](repeating:-1,count:26) 6 let arrS:[Int] = Array(str1).map{$0.ascii} 7 let arrT:[Int] = Array(str2).map{$0.ascii} 8 for i in 0..<n 9 { 10 var x:Int = arrS[i] - 97 11 var y:Int = arrT[i] - 97 12 if arr[x] == -1 13 { 14 arr[x] = y 15 } 16 else if arr[x] != y 17 { 18 return false 19 } 20 } 21 var has:Int = 0 22 for i in 0..<26 23 { 24 if arr[i] != -1 25 { 26 has += 1 27 } 28 } 29 var flag:Int = 0 30 for i in 0..<26 31 { 32 for j in (i + 1)..<26 33 { 34 if arr[i] != -1 && arr[j] != -1 && arr[i] == arr[j] 35 { 36 flag = 1 37 } 38 } 39 } 40 if has != 26 || flag != 0 {return true} 41 return false 42 } 43 } 44 45 //Character扩展 46 extension Character 47 { 48 //Character转ASCII整数值(定义小写为整数值) 49 var ascii: Int { 50 get { 51 return Int(self.unicodeScalars.first?.value ?? 0) 52 } 53 } 54 }