zoukankan      html  css  js  c++  java
  • Given two strings S and T, determine if they are both one edit distance apart

    题目:

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

    i. Modify operation – Modify a character to X in S.
    S = “abcde”
    T = “abXde”


    ii. Insert operation – X was inserted before a character in S.
    S = “abcde”
    T = “abcXde”


    iii. Append operation – X was appended at the end of S.
    S = “abcde”
    T = “abcdeX”

    解答:

     1 public class Solution {
     2 
     3     public static void main(String[] args) {
     4         String s = "abcde";
     5         String t = "abcdeX";
     6 
     7         System.out.println(isOneEditDistance(s, t));
     8     }
     9 
    10     public boolean isOneEditDistance(String s, String t) {
    11         int m = s.length();
    12         int n = t.length();
    13         if(m > n) {
    14             return isOneEditDistance(t, s);
    15         }
    16 
    17         if(n - m > 1) {
    18             return flase;
    19         }
    20 
    21         int i = 0;
    22         shift = n - m;
    23         while(i < m && s.charAt(i) == t.charAt(i)) {
    24             i++;
    25         }
    26 
    27         if(i == m) {
    28             return shift > 0;
    29         }
    30 
    31         if(shift == 0) {
    32             i++;
    33         }
    34 
    35         while(i < m && s.charAt(i) == t.charAt(i+shift)) {
    36             i++;
    37         }
    38 
    39         return i == m;
    40     }
    41 
    42 }

  • 相关阅读:
    147-21. 合并两个有序链表
    146-14. 最长公共前缀
    145-如何查看python帮助文档
    144-38. 外观数列
    143-121. 买卖股票的最佳时机
    142-206. 反转链表
    141-98. 验证二叉搜索树
    Nginx中文域名配置
    Keepalived+Nginx架构整理版
    Tomcat启动脚本
  • 原文地址:https://www.cnblogs.com/wylwyl/p/10397310.html
Copyright © 2011-2022 走看看