返回介绍

solution / 1500-1599 / 1554.Strings Differ by One Character / README_EN

发布于 2024-06-17 01:03:18 字数 3395 浏览 0 评论 0 收藏 0

1554. 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.

Solutions

Solution 1

class Solution:
  def differByOne(self, dict: List[str]) -> bool:
    s = set()
    for word in dict:
      for i in range(len(word)):
        t = word[:i] + "*" + word[i + 1 :]
        if t in s:
          return True
        s.add(t)
    return False
class Solution {
  public boolean differByOne(String[] dict) {
    Set<String> s = new HashSet<>();
    for (String word : dict) {
      for (int i = 0; i < word.length(); ++i) {
        String t = word.substring(0, i) + "*" + word.substring(i + 1);
        if (s.contains(t)) {
          return true;
        }
        s.add(t);
      }
    }
    return false;
  }
}
class Solution {
public:
  bool differByOne(vector<string>& dict) {
    unordered_set<string> s;
    for (auto word : dict) {
      for (int i = 0; i < word.size(); ++i) {
        auto t = word;
        t[i] = '*';
        if (s.count(t)) return true;
        s.insert(t);
      }
    }
    return false;
  }
};
func differByOne(dict []string) bool {
  s := make(map[string]bool)
  for _, word := range dict {
    for i := range word {
      t := word[:i] + "*" + word[i+1:]
      if s[t] {
        return true
      }
      s[t] = true
    }
  }
  return false
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文