If two strings differ by exactly one character at the same index, then if we replace that character with a wildcard (e.g., ‘*’), the resulting string will be the same for both. We can use a hash set to check for such collisions efficiently.
For each string, for each index, replace the character at that index with a wildcard and check if this new string has been seen before. If yes, return true. Otherwise, add it to the set. If no such pair is found, return false.
#include<vector>#include<string>#include<unordered_set>usingnamespace std;
classSolution {
public:bool differByOne(vector<string>& dict) {
unordered_set<string> seen;
int m = dict[0].size();
for (const string& word : dict) {
for (int i =0; i < m; ++i) {
string t = word;
t[i] ='*';
if (seen.count(t)) return true;
seen.insert(t);
}
}
return false;
}
};
import java.util.*;
classSolution {
publicbooleandifferByOne(String[] dict) {
Set<String> seen =new HashSet<>();
int m = dict[0].length();
for (String word : dict) {
for (int i = 0; i < m; i++) {
String t = word.substring(0, i) +"*"+ word.substring(i+1);
if (seen.contains(t)) returntrue;
seen.add(t);
}
}
returnfalse;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
fundifferByOne(dict: Array<String>): Boolean {
val seen = mutableSetOf<String>()
val m = dict[0].length
for (word in dict) {
for (i in0 until m) {
val t = word.substring(0, i) + "*" + word.substring(i+1)
if (t in seen) returntrue seen.add(t)
}
}
returnfalse}
1
2
3
4
5
6
7
8
9
10
defdifferByOne(dict: list[str]) -> bool:
seen = set()
m = len(dict[0])
for word in dict:
for i in range(m):
t = word[:i] +'*'+ word[i+1:]
if t in seen:
returnTrue seen.add(t)
returnFalse
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
use std::collections::HashSet;
pubfndiffer_by_one(dict: Vec<String>) -> bool {
let m = dict[0].len();
letmut seen = HashSet::new();
for word in&dict {
let bytes = word.as_bytes();
for i in0..m {
letmut t = bytes.to_vec();
t[i] =b'*';
if seen.contains(&t) {
returntrue;
}
seen.insert(t);
}
}
false}
1
2
3
4
5
6
7
8
9
10
11
12
functiondifferByOne(dict: string[]):boolean {
constseen=newSet<string>();
constm=dict[0].length;
for (constwordofdict) {
for (leti=0; i<m; i++) {
constt=word.slice(0, i) +'*'+word.slice(i+1);
if (seen.has(t)) returntrue;
seen.add(t);
}
}
returnfalse;
}