GuilinDev

Lc1554

05 August 2008

1554. Strings Differ by One Character

给定一个字符串列表,其中所有字符串的长度相同。

如果同一索引中有 2 个字符串仅相差 1 个字符,则返回 true,否则返回 false。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
    public boolean differByOne(String[] dict) {
        Set<String> set = new HashSet<>();
        for (String d : dict) {
            for (int i = 0; i < d.length(); i++) {
                StringBuilder sb = new StringBuilder(d);
                sb.setCharAt(i, '*');
                String candidate = sb.toString();
                if (!set.add(candidate)) return true;
            }
        }
        return false;
    }
}

Hashmap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
    public boolean differByOne(String[] dict) {
        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i < dict.length; i++) {
           String str = dict[i];
            for (int j = 0; j < str.length(); j++) {
                String s1 = str.substring(0, j);
                String s2 = str.substring(j + 1);
                String s = s1 + "*" + s2;
                if (map.containsKey(s)) {
                    return true;
                }
                
                map.put(s, 1);
            }
        }
        return false;
    }
}