zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    .Net常用的命名空间
    Jquery测试纠错笔记
    第一章 学习总结
    Java和C++引用的区别
    gin的墙内开发艺术
    golang几个环境变量的问题
    Leetcode240_搜索二维矩阵II
    Leetcode1358_包含所有三种字符的子字符串数目
    Leetcode1354_多次求和构造目标数组
    Leetcode1353_最多可以参加的会议数目
  • 原文地址:https://www.cnblogs.com/Pjson/p/8325702.html
Copyright © 2011-2022 走看看