Lintcode C++代码

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

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 j = 0;
        int i = 0;
        if (source == NULL || target == NULL) 
        {
            return -1;
        }
        for (i = 0; source[i] != '\0'; i++) 
       {
            j = 0;
            while (source[i] == target[j] && source[i] != '\0')
            {                   
                j++;
                i++;
            }
            if (target[j] == '\0')
             {
                return i - j;
             }
            i -= j;
      }
        if (i == j && source[i] == target[j]) 
        {
            return i - j;
        }
        return -1;
    }
};

你可能感兴趣的:(Lintcode C++代码)