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.

    Analysis:

    Must be exactly one distance apart. Not the same.

    Solution:

     1 public class Solution {
     2     public boolean isOneEditDistance(String s, String t) {
     3         if (s.length()==0 && t.length()==0) return false;
     4         if (s.length()+t.length()==1) return true;
     5         
     6         if (Math.abs(s.length()-t.length())>1) return false;        
     7 
     8         if (s.length()==t.length()) return isOneReplace(s,t);
     9 
    10         if (s.length()>t.length()) return isOneInsert(s,t);
    11         else return isOneInsert(t,s);
    12         
    13     }
    14 
    15     public boolean isOneInsert(String a, String b){
    16         //a is 1 char longer than b, we determine whether a and b is one insertion distance.
    17 
    18         boolean modified = false;
    19 
    20         int index1 = 0;
    21         int index2 = 0;
    22 
    23         while (index2<b.length()){
    24             if (a.charAt(index1)==b.charAt(index2)){
    25                 index1++;
    26                 index2++;
    27             } else {
    28                 if (modified) return false;
    29                 else {
    30                     index1++;
    31                     modified = true;
    32                 }
    33             }
    34         }
    35         return true;
    36     }
    37 
    38 
    39     public boolean isOneReplace(String a, String b){
    40         //a and b have the same length, we determine whether they are one replace aparted.
    41         boolean modified = false;
    42         int index1=0;
    43         while (index1<a.length())
    44             if (a.charAt(index1)==b.charAt(index1))
    45                 index1++;
    46             else if (modified) return false;
    47             else {
    48                 index1++;
    49                 modified = true;
    50             }
    51         if (modified) return true;
    52         else return false;
    53     }
    54               
    55  
    56         
    57     
    58 }
  • 相关阅读:
    spring19
    springmvc19
    Android打开数据库读取数据
    家庭记账本开发第二天
    家庭记账本开发第一天
    体温填报小程序完结
    一个抽取百度定位的教程(下载百度地图Demo+配置+抽取)
    将百度地图Demo抽取出来安到自己的程序中
    Android定位
    体温数据上传程序开发+获取时间的三种方法+DB Browser下载及安装
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4164065.html
Copyright © 2011-2022 走看看