Leetcode Implement strStr() My Submissions

来源:互联网 发布:unity3d ongui button 编辑:程序博客网 时间:2024/06/16 13:57

Implement strStr()

 My Submissions

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

这个题没点难度,但是考虑得不够全,提交了好几次.

坑有这么几个:

1.needle可能啥也没有.

2.可能needle 的长度大于 haystack

3.可以走着走着到最后了.

说白了,关键还是长度,长度,长度....


public class Solution {    public String strStr(String haystack, String needle) {        if (haystack == null){            return null;        }        if (needle == null || needle.equals("")){            return haystack;        }        if (needle.length() > haystack.length()){            return null;        }        int leng = 0;        for (int i = 0; i < haystack.length(); i++){            if (needle.charAt(0) == haystack.charAt(i)){                leng = needle.length() - 1;                for (int j = 1; j < needle.length(); j++){                    if (i + j > haystack.length() - 1){                        return null;                    }                    if (needle.charAt(j) == haystack.charAt(i + j)){                        leng--;                    }                }                if (leng == 0){                    return haystack.substring(i);                }            }        }        return null;    }}


0 0