题目描述:
Given two strings str1 and str2 of the same length, determine whether you can transform str1 into str2 by doing zero or more conversions.
In one conversion you can convert all occurrences of one character in str1 to any other lowercase English character.
Return true if and only if you can transform str1 into str2.
Example 1:
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:
Input: str1 = "leetcode", str2 = "codeleet" Output: false Explanation: There is no way to transform str1 to str2.
Note:
1 <= str1.length == str2.length <= 10^4- Both
str1andstr2contain only lowercase English letters.
class Solution {
public:
bool canConvert(string str1, string str2) {
// str1相对于str2的字符,可以多对一,不能一对多
unordered_map<char,int> conversion;
unordered_set<char> s1, s2;
for(int i=0;i<str1.size();i++)
{ // 保证一对一或者多对一
if(conversion.count(str1[i])&&conversion[str1[i]]!=str2[i])
return false;
else conversion[str1[i]]=str2[i];
s1.insert(str1[i]);
s2.insert(str2[i]);
}
// s1的字母种类数必须大于等于s2
if(s1.size()<s2.size()) return false;
// 当s1的字母种类数大于s2的时候,必然是合法的
else if(s1.size()>s2.size()) return true;
else // 当s1的字母种类数等于s2时,可能可以利用其他未用过的字母作为桥梁
{ // 但是当字符串包含了全部26个字母时,str1必须等于str2
// 否则一旦转换一个字母,str1中就只有25种字母
if(s2.size()==26) return str1==str2;
else return true;
}
}
};
这道LeetCode题目要求判断在允许进行0次或多次字符转换的情况下,是否能将字符串s转换成字符串t。每次转换可以将s中的任意一个字符替换为其他任意小写字母。如果可以完成转换,则返回true,否则返回false。给定了两个长度相等的英文字符串作为例子进行说明。
277

被折叠的 条评论
为什么被折叠?



