LintCode 13. Implement strStr()

题目描述

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

C++ 实现

class Solution {
public:
    /*
     * @param source: source string to be scanned.
     * @param target: target string containing the sequence of characters to match
     * @return: a index to the first occurrence of target in source, or -1  
                if target is not part of source.
     */
    int strStr(const char *source, const char *target) {
        // write your code here
        if(source==NULL||target==NULL) return -1;
        int s_len = strlen(source);
        int t_len = strlen(target);
        int i = 0;
        int j = 0;
        while(i<s_len&&j<t_len){
            if(source[i]==target[j]){
                i++;
                j++;
            }else{
                i = i-j+1;
                j = 0;
            }
        }
        if(j==t_len)        
            return i-j;
        return -1;
    }
};

相关文章:

  • 2021-06-10
  • 2021-08-06
  • 2021-12-16
  • 2021-12-05
  • 2021-07-18
猜你喜欢
  • 2021-08-16
  • 2021-05-23
  • 2021-11-15
  • 2021-09-19
相关资源
相似解决方案