13 strStr

題目:
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.

思路:

代碼:

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 target_size = strlen(target);
        int source_size = strlen(source);
        int i, j;
        
        //只需要看到 s - t ,應為超過的話就不可能存在完整的 target 
        for (i = 0; i < source_size - target_size + 1; i++) {
            for (j = 0; j < target_size; j++) {
                if (source[i + j] != target[j]) {
                    break;
                }
            }
            //對了才回
            if (j == target_size) {
                return i;
            }
        }
        return -1; 
    }
};

你可能感兴趣的:(13 strStr)