1. 程式人生 > >[leetcode]161. One Edit Distance編輯步數為一 [leetcode]72. Edit Distance 最少編輯步數

[leetcode]161. One Edit Distance編輯步數為一 [leetcode]72. 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 }