leetcode(57)- Implement strStr()

题目:

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

思路:

  • 题意:判断一个字符串是否包含另外一个
  • 写一个函数判断一个字符串从坐标k,是否相等于另一个,遍历一下,i < a.length() -b.length()+1,b。length() < a.length()
    -

代码:

public class Solution {
    public int strStr(String haystack, String needle) {
        if(haystack == null||needle == null||needle.length() > haystack.length()){
            return -1;
        }
        for(int a = 0;a < (haystack.length() - needle.length()+1);a++){
            if(equal(haystack,a,needle)){
                return a;
            }
        }
        return -1;
    }
    public boolean equal(String a,int k,String b){
        for(int m = 0;m < b.length();m++){
            if(b.charAt(m) != a.charAt(k)){
                return false;
            }
            k++;
        }
        return true;
    }
}

你可能感兴趣的:(LeetCode,算法,面试,strstr,implement)