写bug-free 的code

一个算法题目 写的没有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;
        
    }


通过这个例子,我觉得写代码时候着急不得,把变量的适用条件都考虑清楚了,前后关系都要想清楚了


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值