zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    chrome 修改请求头的小工具
    spring boot整合shiro引用配置文件配置是出现的问题
    jquery ztree 复选框
    表单input中disabled提交后得不到值的解决办法
    大文件编辑器
    记一次差点删库跑路的事故
    简单的记录一次简单的优化
    mysql 死锁解决办法
    centos6,7中防火墙基本用法
    案例3-ubuntu和centos中自动部署tomcat相关服务的脚本
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5817839.html
Copyright © 2011-2022 走看看