zoukankan      html  css  js  c++  java
  • [LC] 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.


    class Solution {
        public boolean isOneEditDistance(String s, String t) {
            if (Math.abs(s.length() - t.length()) > 1) {
                return false;
            }
            if (s.length() == t.length()) {
                return isOneModify(s, t);
            } else if (s.length() > t.length()) {
                return isOneDel(s, t);
            } else {
                return isOneDel(t, s);
            }
        }
        
        private boolean isOneModify(String s, String t) {
            int diff = 0, i = 0;
            while (i < s.length()) {
                if (s.charAt(i) != t.charAt(i)) {
                    diff += 1;
                }
                i += 1;
            }
            return diff == 1;
        }
        
        private boolean isOneDel(String s, String t) {
            int i = 0;
            for (; i < s.length() && i < t.length(); i++) {
                if (s.charAt(i) != t.charAt(i)) {
                    break;
                }
            }
            return s.substring(i + 1).equals(t.substring(i));
        }
    }
  • 相关阅读:
    若不曾忘记,便不必追忆
    C# 随机生成中文字符串
    C# SQLiteHelper
    C# SQLHelper
    C# Microsoft SQL Server 操作
    C# Excel 操作
    C# XML文件操作(续)
    C# 遍历XML文件,添加,更新,删除节点
    MES系统简介
    SQL Server 存储过程(转)
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12144340.html
Copyright © 2011-2022 走看看