问题:对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1

 

字符串查找的算法有不止一种,一般情况下,面试官会只让你写出最简单的朴素算法,而不要求写出效率更高的KMP算法。所以我解决这道题用的也将是朴素算法,至于KMP算法,详情可以参照我的另一篇博文:简单理解KMP算法

 

参考代码:

<code class="language-c++" cs="" hljs="">class Solution {
public:
    /**
     * Returns a index to the first occurrence of target in source,
     * or -1  if target is not part of source.
     * @param source string to be scanned.
     * @param target string containing the sequence of characters to match.
     */
    int strStr(const char *source, const char *target) {
        // write your code here
        int i = 0, j = 0;
        if (source == NULL || target == NULL)
            return -1;
        while (source[i] != ''&&target[j] != '') {
            if (source[i] == target[j]) {
                i++;
                j++;
            } else {
                i = i - j + 1;
                j = 0;
            }
        }
        if (target[j] == '')
            return i - j;
        return -1;
    }
};</code>
 posted on 2018-01-21 21:41  做个快乐的自己  阅读(138)  评论(0编辑  收藏  举报