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
     if (source == NULL || target == NULL) {
         return -1;
     }
        int i = 0, j = 0;

      while(*(source + i) && *(target + j)){
          if(*(source + i) == *(target + j)){
              ++ i;
             ++ j;
          }
         else{
             i = i - j + 1;   //i 回溯到上一轮的下一个
             j = 0;           //j 从第一个开始比较
         }
     }
     if(*(target + j) == '\0')
         return  i -  j;
     else
         return -1;
 }

};

results matching ""

    No results matching ""