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 }
  • 相关阅读:
    联考20200520 T2 函数
    联考20200520 T1 石子游戏
    模拟赛T2 中继系统
    模拟赛T2 仙人掌毒题
    BZOJ3462 DZY Loves Math II
    20200129模拟赛T1 string
    BZOJ1316 树上的询问
    BZOJ4559 成绩比较
    JZOJ4238 纪念碑
    BZOJ 2648 世界树
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4164065.html
Copyright © 2011-2022 走看看