摘要:比較長度法復(fù)雜度時間空間思路雖然我們可以用的解法,看是否為,但中會超時。這里我們可以利用只有一個不同的特點(diǎn)在時間內(nèi)完成。
One Edit Distance
Given two strings S and T, determine if they are both one edit distance apart.比較長度法 復(fù)雜度
時間 O(N) 空間 O(1)
思路雖然我們可以用Edit Distance的解法,看distance是否為1,但Leetcode中會超時。這里我們可以利用只有一個不同的特點(diǎn)在O(N)時間內(nèi)完成。如果兩個字符串只有一個編輯距離,則只有兩種情況:
兩個字符串一樣長的時候,說明有一個替換操作,我們只要看對應(yīng)位置是不是只有一個字符不一樣就行了
一個字符串比另一個長1,說明有個增加或刪除操作,我們就找到第一個對應(yīng)位置不一樣的那個字符,如果較長字符串在那個字符之后的部分和較短字符串那個字符及之后的部分是一樣的,則符合要求
如果兩個字符串長度差距大于1,肯定不對
代碼public class Solution { public boolean isOneEditDistance(String s, String t) { int m = s.length(), n = t.length(); if(m == n) return isOneModified(s, t); if(m - n == 1) return isOneDeleted(s, t); if(n - m == 1) return isOneDeleted(t, s); // 長度差距大于2直接返回false return false; } private boolean isOneModified(String s, String t){ boolean modified = false; // 看是否只修改了一個字符 for(int i = 0; i < s.length(); i++){ if(s.charAt(i) != t.charAt(i)){ if(modified) return false; modified = true; } } return modified; } public boolean isOneDeleted(String longer, String shorter){ // 找到第一組不一樣的字符,看后面是否一樣 for(int i = 0; i < shorter.length(); i++){ if(longer.charAt(i) != shorter.charAt(i)){ return longer.substring(i + 1).equals(shorter.substring(i)); } } return true; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/64723.html
摘要:復(fù)雜度思路考慮如果兩個字符串的長度,是肯定當(dāng)兩個字符串中有不同的字符出現(xiàn)的時候,說明之后的字符串一定要相等。的長度比較大的時候,說明的時候,才能保證距離為。 LeetCode[161] One Edit Distance Given two strings S and T, determine if they are both one edit distance apart. Stri...
摘要:動態(tài)規(guī)劃復(fù)雜度時間空間思路這是算法導(dǎo)論中經(jīng)典的一道動態(tài)規(guī)劃的題。 Edit Distance Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.) You h...
摘要:構(gòu)造數(shù)組,是的,是的,是將位的轉(zhuǎn)換成位的需要的步數(shù)。初始化和為到它們各自的距離,然后兩次循環(huán)和即可。 Problem Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 s...
摘要:復(fù)雜度思路考慮用二維來表示變換的情況。如果兩個字符串中的字符相等,那么如果兩個字符串中的字符不相等,那么考慮不同的情況表示的是,從字符串到的位置轉(zhuǎn)換到字符串到的位置,所需要的最少步數(shù)。 LeetCode[72] Edit Distance Given two words word1 and word2, find the minimum number of steps require...
摘要:題目要求輸入兩個字符串和,允許對進(jìn)行插入,刪除和替換的操作,計(jì)算出將轉(zhuǎn)化為所需要的最少的操作數(shù)。其中存儲的是轉(zhuǎn)換為的最小步數(shù)。首先從邊緣情況開始考慮。只要在此基礎(chǔ)上再進(jìn)行一次插入操作即可以完成轉(zhuǎn)換。 題目要求 Given two words word1 and word2, find the minimum number of steps required to convert wor...
閱讀 2112·2023-04-26 02:41
閱讀 2155·2021-09-24 09:47
閱讀 1562·2019-08-30 15:53
閱讀 1216·2019-08-30 13:01
閱讀 1896·2019-08-29 11:27
閱讀 2872·2019-08-28 17:55
閱讀 1781·2019-08-26 14:00
閱讀 3396·2019-08-26 10:18