For a given source string and a target string, you should output the first index(from 0) of target string in source string.

If target does not exist in source, just return-1.

思路:

这个题目是一道经典题,我们没有必要纠结于KMP算法。两层for循环+two pointers的算法如果能bug-free就很好了。

外层for循环 遍历每一个char in source 作为检测target的起始点,最后的临界点是个重点: source.length - target.length + 1,同样的写法我们在 two sum 里也用过。可以这样记:两个length相减就导致多减了一个1,因此还要加上。

内层for循环 就是用第二个指针走一遍target。

public int strStr(String source, String target) {
        //write your code here
        if (source == null || target == null )
            return -1;


        for (int i = 0; i < source.length() - target.length() + 1; i++) {
            int j = 0;
            for ( j = 0; j < target.length(); j++) {
                    if (source.charAt(i+j) != target.charAt(j))
                        break;
            }

            if ( j == target.length())
                    return i;
        }

        return -1;
    }

results matching ""

    No results matching ""