首页 > 其他 > 详细

String字符串查找

时间:2018-05-01 22:42:14      阅读:245      评论:0      收藏:0      [点我收藏+]

字符串专题

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

String字符串查找

原文:https://www.cnblogs.com/hglibin/p/8977223.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!