• LeetCode-One Edit Distance


    Given two strings S and T, determine if they are both one edit distance apart.

    Solution 1:

     1 public class Solution {
     2     public boolean isOneEditDistance(String s, String t) {
     3         if ((s.isEmpty() && t.isEmpty()) || Math.abs(s.length() - t.length()) > 1)
     4             return false;
     5 
     6         if (s.length() == t.length()) {
     7             return isOneReplace(s, t);
     8         }
     9 
    10         if (s.length() > t.length()) {
    11             return isOneInsert(t, s);
    12         } else {
    13             return isOneInsert(s, t);
    14         }
    15     }
    16 
    17     public boolean isOneReplace(String s, String t) {
    18         boolean foundDiff = false;
    19         for (int i = 0; i < s.length(); i++)
    20             if (s.charAt(i) != t.charAt(i)) {
    21                 if (foundDiff)
    22                     return false;
    23                 foundDiff = true;
    24             }
    25         return foundDiff;
    26 
    27     }
    28 
    29     public boolean isOneInsert(String small, String large) {
    30         boolean hasSkip = false;
    31         int p1 = 0, p2 = 0;
    32         while (p1 < small.length() && p2 < large.length()) {
    33             if (small.charAt(p1) != large.charAt(p2)) {
    34                 if (hasSkip)
    35                     return false;
    36                 hasSkip = true;
    37                 p2++;
    38             } else {
    39                 p1++;
    40                 p2++;
    41             }
    42         }
    43         return true;
    44     }
    45 }

    NOTE: this solution is too much for this question. We can simply fetch substring and compare.

    Solution 2:

     1 public class Solution {
     2     public boolean isOneEditDistance(String s, String t) {
     3         int m = s.length();
     4         int n = t.length();
     5         if (Math.abs(m - n) > 1) {
     6             return false;
     7         }
     8 
     9         int len = Math.min(m, n);
    10         for (int i = 0; i < len; i++) {
    11             if (s.charAt(i) != t.charAt(i)) {
    12                 boolean result = s.substring(i).equals(t.substring(i + 1));
    13                 result = result || s.substring(i + 1).equals(t.substring(i));
    14                 result = result || s.substring(i + 1).equals(t.substring(i + 1));
    15                 return result;
    16             }
    17         }
    18         return Math.abs(m - n) == 1;
    19     }
    20 }
  • 相关阅读:
    android 控件: xml 设置 Button 按下背景
    Hadoop: the definitive guide 第三版 拾遗 第四章
    二进制日志占满空间
    Unity3d学习笔记记录
    百度地图api---实现新建地图
    php简单浏览目录内容
    CRC校验的实现
    Android记录3--ExpandableListView使用+获取SIM卡状态信息
    Zookeeper Api(java)入门与应用(转)
    ZooKeeper程序员指南(转)
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5817839.html
Copyright © 2020-2023  润新知