• 13. 字符串查找


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

    字符串查找的算法有不止一种,一般情况下,面试官会只让你写出最简单的朴素算法,而不要求写出效率更高的KMP算法。所以我解决这道题用的也将是朴素算法,至于KMP算法,详情可以参照我的另一篇博文:简单理解KMP算法

    参考代码:

    <code class="language-c++" cs="" hljs="">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
            int i = 0, j = 0;
            if (source == NULL || target == NULL)
                return -1;
            while (source[i] != ''&&target[j] != '') {
                if (source[i] == target[j]) {
                    i++;
                    j++;
                } else {
                    i = i - j + 1;
                    j = 0;
                }
            }
            if (target[j] == '')
                return i - j;
            return -1;
        }
    };</code>
  • 相关阅读:
    Java遍历包中所有类方法注解
    mysql字符集问题
    mybatis查询mysql的datetime类型数据时间差了14小时(时区问题)
    mysql 查询的一次bug
    redis分布式锁超时事故
    maven 多个镜像
    maven deploy
    DFS( 修改)
    poj.org --map-- 1002
    nyist 58 最少步数
  • 原文地址:https://www.cnblogs.com/Pjson/p/8325702.html
Copyright © 2020-2023  润新知