String字符串查找

字符串专题

  • 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;
    }
    };

猜你喜欢

转载自www.cnblogs.com/hglibin/p/8977223.html