1st round, 161 One Edit Distance
来源:互联网 发布:手机淘宝差评改好评 编辑:程序博客网 时间:2024/05/16 01:25
快速粘贴,抓紧时间。。。
public class Solution { public boolean isOneEditDistance(String s, String t) { // solution 2 思路: 首先要求对题意理解准确。。。那就是只有一个差字母的相差,相等的也不行,所以首先来找到这个差异。。。只能遍历 // 差异的话,有两种情况,1,长度相等,2,长度差1。。。2情况下,又分类,是中间差还是最后差。。!!注意了,这道题好像忽略了长的string多出一个头部的字母的情况。。。 for(int i=0; i<Math.min(s.length(), t.length()); i++){ if(s.charAt(i)!=t.charAt(i)){ if(s.length()==t.length()) return (s.substring(i+1).equals(t.substring(i+1))); else if(s.length()>t.length()) return (s.substring(i+1).equals(t.substring(i))); else if(t.length()>s.length()) return (t.substring(i+1).equals(s.substring(i))); } } // only if the preString with the same min length substring are the same, the will be nothing return in the for loop // so need to return whether s and t differ in length by 1 return Math.abs(s.length()-t.length())==1; // 1.26.17 以下是我分门别类的写法,倒也是思路清晰,否则写不出这么多分类还一次AC。。 // 但是看了top solution的代码,那叫一个简洁和精炼啊!!所以我也跟着那个思路,写一遍,见上方。。。 // solution 1/* if( (s==null && t==null) || (s.equals("") && t.equals("")) ) return false; if( (s.equals("")&&(t.length()==1)) || (t.equals("")&&(s.length()==1)) ) return true; // length difference over 1, return false if(Math.abs(s.length()-t.length())>1) return false; // equal length if(s.length()-t.length()==0){ int mismatch=0; for(int i=0; i<s.length(); i++){ if(s.charAt(i)!=t.charAt(i)) mismatch++; if(mismatch>1) return false; // 加上这一句,从4ms变到3ms。。。我看了4ms成绩很差,所以回来看有没有省去一些多余的部分 } return mismatch==1?true:false; } else if(s.length()-t.length()==1){ int i=0; for(; i<s.length(); i++){ if(i==s.length()-1) return true; if(s.charAt(i)!=t.charAt(i)) break; } for(i=i+1; i<s.length(); i++){ if(s.charAt(i)!=t.charAt(i-1)) return false; } return true; } else if(t.length()-s.length()==1){ int i=0; for(; i<t.length(); i++){ if(i==t.length()-1) return true; if(t.charAt(i)!=s.charAt(i)) break; } for(i=i+1; i<t.length(); i++){ if(t.charAt(i)!=s.charAt(i-1)) return false; } return true; } return false;*/ }}
0 0
- 1st round, 161 One Edit Distance
- leetcode 161: One Edit Distance
- One Edit Distance
- One Edit Distance
- Leetcode One Edit Distance
- One Edit Distance
- one edit distance python
- LeetCode - One Edit Distance
- One Edit Distance
- leetcode - One Edit Distance
- #leetcode#One Edit Distance
- [LeetCode]One Edit Distance
- [LeetCode161] One Edit Distance
- 161. One Edit Distance
- One Edit Distance
- One Edit Distance
- One Edit Distance
- One Edit Distance
- Redis-benchmark使用总结
- 1100. Mars Numbers (20)
- pyqt4使用qt designer设计的ui文件的方法(将ui文件转换为python源码和类的方法)
- vbgdfg
- apache-ab 并发负载压力测试
- 1st round, 161 One Edit Distance
- CKeditor配置
- java基础之static关键字作用
- 机器学习CART及CCP剪枝原理
- 自定义标签模板
- poj 1013
- css交集选择器、并集选择器、兄弟选择器
- Springboot+Ebean配置Mysql数据源报错
- 洛谷P1223 排队接水