zoukankan      html  css  js  c++  java
  • [LeetCode] 161. One Edit Distance

    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.
    

    Example 3:

    Input: s = "a", t = ""
    Output: true
    

    Example 4:

    Input: s = "", t = "A"
    Output: true

    Constraints:

    • 0 <= s.length <= 104
    • 0 <= t.length <= 104
    • s and t consist of lower-case letters, upper-case letters and/or digits.

    相隔为 1 的编辑距离。

    题意是有两个字符串S和T,请问是否可以通过编辑一个字符,让两者一样。所谓的编辑是可以加一个字符,减一个字符或者改变一个字符。

    因为题干直接告诉了编辑的方式,所以思路还是很直接的。扫描两个字符串,注意有可能两者不是等长的,所以扫描的长度是两者较短的一个。当碰到第一个不同的字符i的时候,判断两者之后剩下的substring是否一样,如果一样,则能满足题意,否则就不满足题意。

    时间O(n^2) - 扫描字符串是O(n),同时比较substring的equal函数也是接近于O(n)的复杂度

    空间O(1)

    Java实现

     1 class Solution {
     2     public boolean isOneEditDistance(String s, String t) {
     3         for (int i = 0; i < Math.min(s.length(), t.length()); i++) {
     4             if (s.charAt(i) != t.charAt(i)) {
     5                 // replace one letter
     6                 if (s.length() == t.length()) {
     7                     return s.substring(i + 1).equals(t.substring(i + 1));
     8                 } else if (s.length() < t.length()) {
     9                     return s.substring(i).equals(t.substring(i + 1));
    10                 } else if (s.length() > t.length()) {
    11                     return t.substring(i).equals(s.substring(i + 1));
    12                 }
    13             }
    14         }
    15         // try to remove the last letter from the longer string
    16         return Math.abs(s.length() - t.length()) == 1;
    17     }
    18 }

    LeetCode 题目总结

  • 相关阅读:
    4.26上午
    4.25下午
    4.19上午
    4.18上午
    7.26
    7.25
    7.21-7.22
    7.22
    7.21
    7.11-7.15
  • 原文地址:https://www.cnblogs.com/cnoodle/p/13515403.html
Copyright © 2011-2022 走看看