LeetCode 1554. Strings Differ by One Character

原题链接在这里:https://leetcode.com/problems/strings-differ-by-one-character/description/

题目:

Given a list of strings dict where all the strings are of the same length.

Return true if there are 2 strings that only differ by 1 character in the same index, otherwise return false.

Example 1:

Input: dict = ["abcd","acbd", "aacd"]
Output: true
Explanation: Strings "abcd" and "aacd" differ only by one character in the index 1.

Example 2:

Input: dict = ["ab","cd","yz"]
Output: false

Example 3:

Input: dict = ["abcd","cccc","abyd","abab"]
Output: true

Constraints:

  • The number of characters in dict <= 105
  • dict[i].length == dict[j].length
  • dict[i] should be unique.
  • dict[i] contains only lowercase English letters.

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.

题解:

For each string in dict, we want to check if remove the same index char, the rest could be duplicate.

We can use the hash value minus the same index char hash and check if there is duplicate.

First calculate the hash for all the strigns in the dict.

Then for each index, we have a set, then iterate each strings in the dict and remove the corresponding index char hash. Check if duplicate can exist and return true if yes.

Time Complexity: O(n * m). n = dict.length. m = dict[0].length().

Space: O(n).

AC Java:

 1 class Solution {
 2     public boolean differByOne(String[] dict) {
 3         if(dict == null || dict.length == 0){
 4             return false;
 5         }
 6 
 7         long mod = (long)Math.pow(10, 20) + 7;
 8         int len = dict[0].length();
 9         int n = dict.length;
10         long[] word2Hash = new long[n];
11         for(int i = 0; i < n; i++){
12             for(int j = 0; j < len; j++){
13                 word2Hash[i] = (word2Hash[i] * 26 + (dict[i].charAt(j) - 'a')) % mod;
14             }
15         }
16 
17         long base = 1;
18         for(int j = len - 1; j >= 0; j--){
19             HashSet<Long> hs = new HashSet<>();
20             for(int i = 0; i < n; i++){
21                 long can = (word2Hash[i] - (base * dict[i].charAt(j) - 'a')) % mod;
22                 if(!hs.add(can)){
23                     return true;
24                 }
25             }
26 
27             base = base * 26 % mod;
28         }
29 
30         return false;
31     }
32 }

 

posted @ 2024-08-04 02:56  Dylan_Java_NYC  阅读(5)  评论(0编辑  收藏  举报