返回介绍

solution / 0100-0199 / 0161.One Edit Distance / README_EN

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

161. One Edit Distance

中文文档

Description

Given two strings s and t, return true if they are both one edit distance apart, otherwise return false.

A string s is said to be one distance apart from a string t if you can:

  • Insert exactly one character into s to get t.
  • Delete exactly one character from s to get t.
  • Replace exactly one character of s with a different character to get t.

 

Example 1:

Input: s = "ab", t = "acb"
Output: true
Explanation: We can insert 'c' into s to get t.

Example 2:

Input: s = "", t = ""
Output: false
Explanation: We cannot get t from s by only one step.

 

Constraints:

  • 0 <= s.length, t.length <= 104
  • s and t consist of lowercase letters, uppercase letters, and digits.

Solutions

Solution 1

class Solution:
  def isOneEditDistance(self, s: str, t: str) -> bool:
    if len(s) < len(t):
      return self.isOneEditDistance(t, s)
    m, n = len(s), len(t)
    if m - n > 1:
      return False
    for i, c in enumerate(t):
      if c != s[i]:
        return s[i + 1 :] == t[i + 1 :] if m == n else s[i + 1 :] == t[i:]
    return m == n + 1
class Solution {
  public boolean isOneEditDistance(String s, String t) {
    int m = s.length(), n = t.length();
    if (m < n) {
      return isOneEditDistance(t, s);
    }
    if (m - n > 1) {
      return false;
    }
    for (int i = 0; i < n; ++i) {
      if (s.charAt(i) != t.charAt(i)) {
        if (m == n) {
          return s.substring(i + 1).equals(t.substring(i + 1));
        }
        return s.substring(i + 1).equals(t.substring(i));
      }
    }
    return m == n + 1;
  }
}
class Solution {
public:
  bool isOneEditDistance(string s, string t) {
    int m = s.size(), n = t.size();
    if (m < n) return isOneEditDistance(t, s);
    if (m - n > 1) return false;
    for (int i = 0; i < n; ++i) {
      if (s[i] != t[i]) {
        if (m == n) return s.substr(i + 1) == t.substr(i + 1);
        return s.substr(i + 1) == t.substr(i);
      }
    }
    return m == n + 1;
  }
};
func isOneEditDistance(s string, t string) bool {
  m, n := len(s), len(t)
  if m < n {
    return isOneEditDistance(t, s)
  }
  if m-n > 1 {
    return false
  }
  for i := range t {
    if s[i] != t[i] {
      if m == n {
        return s[i+1:] == t[i+1:]
      }
      return s[i+1:] == t[i:]
    }
  }
  return m == n+1
}

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

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

发布评论

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