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

    原题链接在这里:https://leetcode.com/problems/one-edit-distance/

    题目:

    Given two strings s and t, determine if they are both one edit distance apart.

    Note: 

    There are 3 possiblities to satisify one edit distance apart:

    1. Insert a character into s to get t
    2. Delete a character from s to get t
    3. Replace a character of s 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 = "cab", t = "ad"
    Output: false
    Explanation: We cannot get t from s by only one step.

    Example 3:

    Input: s = "1203", t = "1213"
    Output: true
    Explanation: We can replace '0' with '1' to get t.

    题解:

    若是长度相差大于1, return false. 若是长度相差等于1, 遇到不同char时, 长的那个向后挪一位. 若是长度相等, 遇到不同char时同时向后挪一位.

    出了loop还没有返回,就是到目前为止都相同,那么看长度差是不是等于1. 这里等于0表示完全相同也不可以.

    Time Complexity: O(Math.min(len1, len2)).

    Space: O(1).

    AC Java:

     1 public class Solution {
     2     public boolean isOneEditDistance(String s, String t) {
     3         if(s == null || t == null){
     4             return false;
     5         }
     6         int len1 = s.length();
     7         int len2 = t.length();
     8         for(int i = 0; i < Math.min(len1, len2); i++){
     9             if(s.charAt(i) != t.charAt(i)){
    10                 if(len1 == len2){
    11                     return s.substring(i+1).equals(t.substring(i+1));
    12                 }else if(len1 > len2){
    13                     return s.substring(i+1).equals(t.substring(i));
    14                 }else{
    15                     return s.substring(i).equals(t.substring(i+1));
    16                 }
    17             }
    18         }
    19         return Math.abs(len1-len2) == 1;
    20     }
    21 }

    类似Edit Distance

  • 相关阅读:
    Hibernate缓存策略
    Hibernate初探之一对多映射 及 myeclipse自动生成hibernate文件方法
    Hibernate初探之单表映射
    01箱包问题
    oracle备份恢复
    旅游参考
    Linux中find常见用法示例
    oracle 比较两个用户表结构的区别。
    SSH自动断开连接的原因
    在Oracle中查看客户端连接的IP信息 .
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/5206021.html
Copyright © 2011-2022 走看看