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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
2022-08-04 LeetCode 1400. Construct K Palindrome Strings
2022-08-04 LeetCode 1950. Maximum of Minimum Values in All Subarrays
2022-08-04 LeetCode 2187. Minimum Time to Complete Trips
2022-08-04 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit
2019-08-04 LeetCode 841. Keys and Rooms
2019-08-04 LeetCode 1061. Lexicographically Smallest Equivalent String
2019-08-04 LeetCode 1102. Path With Maximum Minimum Value