首页 > 其他 > 详细

LeetCode One Edit Distance

时间:2016-02-22 07:50:00      阅读:123      评论:0      收藏:0      [点我收藏+]

原题链接在这里:https://leetcode.com/problems/one-edit-distance/

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

Edit Distance类似。

若是长度相差大于1, return false. 若是长度相差等于1, 遇到不同char时, 长的那个向后挪一位. 若是长度相等, 遇到不同char时同时向后挪一位.

出了loop还没有返回,就是到目前为止都相同,那么看长度差是不是等于1. 这里等于0表示完全相同也不可以.

Time Complexity: O(Math.min(len1, len2)). Space: O(1).

AC Java:

 1 public class Solution {
 2     public boolean isOneEditDistance(String s, String t) {
 3         if(s == null || t == null){
 4             return false;
 5         }
 6         int len1 = s.length();
 7         int len2 = t.length();
 8         for(int i = 0; i < Math.min(len1, len2); i++){
 9             if(s.charAt(i) != t.charAt(i)){
10                 if(len1 == len2){
11                     return s.substring(i+1).equals(t.substring(i+1));
12                 }else if(len1 > len2){
13                     return s.substring(i+1).equals(t.substring(i));
14                 }else{
15                     return s.substring(i).equals(t.substring(i+1));
16                 }
17             }
18         }
19         return Math.abs(len1-len2) == 1;
20     }
21 }

 

LeetCode One Edit Distance

原文:http://www.cnblogs.com/Dylan-Java-NYC/p/5206021.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!