Lintcode C++コード

2235 ワード

検索文字列指定された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;
    }
};