zoukankan      html  css  js  c++  java
  • [leetcode]161. One Edit Distance编辑步数为一

    Given two strings s and t, determine if they are both one edit distance apart.

    Note: 

    There are 3 possiblities to satisify one edit distance apart:

    1. Insert a character into s to get t
    2. Delete a character from s to get t
    3. Replace a character of s to get t

    Example 1:

    Input: s = "ab", t = "acb"
    Output: true
    Explanation: We can insert 'c' into s to get t.
    

    Example 2:

    Input: s = "cab", t = "ad"
    Output: false
    Explanation: We cannot get t from s by only one step.

    Example 3:

    Input: s = "1203", t = "1213"
    Output: true
    Explanation: We can replace '0' with '1' to get t.

    题目

    给定两个字符串,判断其编辑步数是否为1

    思路

    此题可算是[leetcode]72. Edit Distance 最少编辑步数的一个拆分简化版本

    代码

     1 class Solution {
     2      public boolean isOneEditDistance(String s, String t) {
     3         int m = s.length(), n = t.length();
     4         if(m == n) return isOneModified(s, t);
     5         if(m - n == 1) return isOneDeleted(s, t);
     6         if(n - m == 1) return isOneDeleted(t, s);
     7         // 长度差距大于2直接返回false
     8         return false;
     9     }
    10     
    11     private boolean isOneModified(String s, String t){
    12         boolean modified = false;
    13         // 看是否只修改了一个字符
    14         for(int i = 0; i < s.length(); i++){
    15             if(s.charAt(i) != t.charAt(i)){
    16                 if(modified) return false;
    17                 modified = true;
    18             }
    19         }
    20         return modified;
    21     }
    22     
    23     public boolean isOneDeleted(String longer, String shorter){
    24         // 找到第一组不一样的字符,看后面是否一样
    25         for(int i = 0; i < shorter.length(); i++){
    26             if(longer.charAt(i) != shorter.charAt(i)){
    27                 return longer.substring(i + 1).equals(shorter.substring(i));
    28             }
    29         }
    30         return true;
    31     }
    32 }
  • 相关阅读:
    Linux 技巧:让进程在后台可靠运行的几种方法
    What is /dev/null 2>&1?
    In the shell, what does “ 2>&1 ” mean?
    Linux命令之umask
    /dev/null简介
    What is special about /dev/tty?
    sed用法
    cobbler 更换dns和dhcp服务器为dnsmasq
    Linux下如何退出vim的一些常用命令总结
    nginx部署vue项目
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9823989.html
Copyright © 2011-2022 走看看