class Solution:
def differByOne(self, dict):
seen = set()
for word in dict:
for i in range(len(word)):
pattern = word[:i] + '*' + word[i+1:]
if pattern in seen:
return True
seen.add(pattern)
return False
class Solution {
public:
bool differByOne(vector<string>& dict) {
unordered_set<string> seen;
for (const string& word : dict) {
for (int i = 0; i < word.size(); ++i) {
string pattern = word.substr(0, i) + "*" + word.substr(i + 1);
if (seen.count(pattern)) return true;
seen.insert(pattern);
}
}
return false;
}
};
class Solution {
public boolean differByOne(String[] dict) {
Set<String> seen = new HashSet<>();
for (String word : dict) {
for (int i = 0; i < word.length(); ++i) {
String pattern = word.substring(0, i) + "*" + word.substring(i + 1);
if (seen.contains(pattern)) return true;
seen.add(pattern);
}
}
return false;
}
}
var differByOne = function(dict) {
const seen = new Set();
for (const word of dict) {
for (let i = 0; i < word.length; ++i) {
let pattern = word.slice(0, i) + "*" + word.slice(i + 1);
if (seen.has(pattern)) return true;
seen.add(pattern);
}
}
return false;
};
dict
, determine if there exist two strings in the list that differ by exactly one character at the same position. In other words, you need to check if it is possible to pick two different strings from dict
such that, for some index, all characters are the same except for that index. Each string in dict
is of the same length, and you must not compare a string with itself.
*
) in both strings will result in the same pattern. For example, "abcd" and "abed" both become "ab*d" when the third character is replaced.
dict
.*
).True
.False
.dict = ["abcd", "abed", "aecd"]
:
True
.
O(N^2 * L)
, where N
is the number of strings and L
is the length of each string.N
strings, we generate L
patterns, each taking O(L)
time to create and insert/check in the set. So, total time is O(N * L^2)
.N * L
patterns in the set, so space is O(N * L)
.