您的位置:首页 > 其它

写bug-free 的code

2014-10-28 14:26 295 查看
一个算法题目 写的没有bug,是件不容易的事情

必须要考虑全面,其实就是你算法过程中,每个变量是否适用,你的算法是在什么样的前提下面展开的

这个和参数检查是另外一件事情,参数检查被说的好像是一个必须要做的过程,其实这个跟具体实现由关系

如果具体实现无关参数,那就不需要做什么参数检查

比方说 很多时候都要检查传入参数是不是null,如果函数要取这个地址的值,那必须要检查这个指针是否是null,这跟参数检查无关

举个例子


Implement strStr()

 

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
这个是leetcode上面的一个题目,咱们就写最暴力的方法,但是做到bug-free也不是要很仔细的
我第一次的代码是 

public String strStr(String haystack, String needle) {
for (int i = 0; i < haystack.length(); i++) {
for(int j = 0;j<needle.length();j++){
if(haystack.charAt(i+j) == needle.charAt(j)){
if(j == needle.length() -1)
return haystack.substring(i);
else
continue;
}else{
break;
}
}

}
return null;
}


这个错误是考虑不全面,其实在写i+j 时候就该考虑 i+j 是不是越界了。

看我的第二次代码

public String strStr(String haystack, String needle) {
if(haystack == null || haystack.length() == 0){
return null;
}
if(needle == null || needle.length() == 0){
return haystack;
}
for (int i = 0; i < haystack.length(); i++) {
for(int j = 0;j<needle.length();j++){
if(i + j >= haystack.length()) return null;
if(haystack.charAt(i+j) == needle.charAt(j)){
if(j == needle.length() -1)
return haystack.substring(i);
else
continue;
}else{
break;
}
}

}
return null;}


这次几乎就是正确了,但是还是没过,把最开始那两句调整了位置,就过去了。最后代码如下。

public String strStr(String haystack, String needle) {
if(needle == null || needle.length() == 0){
return haystack;
}
if(haystack == null || haystack.length() == 0){
return null;
}

for (int i = 0; i < haystack.length(); i++) {
for(int j = 0;j<needle.length();j++){
if(i + j >= haystack.length()) return null;
if(haystack.charAt(i+j) == needle.charAt(j)){
if(j == needle.length() -1)
return haystack.substring(i);
else
continue;
}else{
break;
}
}

}
return null;

}


通过这个例子,我觉得写代码时候着急不得,把变量的适用条件都考虑清楚了,前后关系都要想清楚了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法