1554. Strings Differ by One Character
1. naive
1.
BruteForce, check all pairs and verify if they differ in one character.
O(n^2 * m) where n is the number of words and m is the length of each string.class Solution {
public boolean differByOne(String[] dict) {
int n = dict.length;
for (int i = 0; i < n ;i++) {
for (int j = i+1; j < n; j++) {
int count = 0;
for (int w = 0 ; w < dict[i].length(); w++) {
if (dict[i].charAt(w) != dict[j].charAt(w)) {
count++;
}
}
if (count == 1) {
return true;
}
}
}
return false;
}
}2.use hashset
Follow up: Could you solve this problem in O(n * m) where n is the length of dict and m is the length of each string.
using rolling hash, put string in hashset
Previous833. Find And Replace in StringNext846. Hand of Straights, 1296. Divide Array in Sets of K Consecutive Numbers
Last updated
Was this helpful?