zoukankan      html  css  js  c++  java
  • 28. Implement strStr()

    description:

    mplement strStr().

    Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
    Note:

    Example:

    Example 1:
    
    Input: haystack = "hello", needle = "ll"
    Output: 2
    Example 2:
    
    Input: haystack = "aaaaa", needle = "bba"
    Output: -1
    

    my answer:

    感恩

    my answer:

    class Solution {
    public:
        int strStr(string haystack, string needle) {
            if(needle.size() == 0) return 0;
            if(haystack.size() < needle.size()) return -1;//这里所有的特殊情况都要考虑周全,刚开始就没想到
            for(int i = 0; i <= haystack.size() - needle.size() ; i++){
                //这里注意i的循环范围,其中有一个测试是两个字符串都是一大长串的aaaaaaa长到一个一个比就oom了,但是其实他们相差的不是很多
                for(int j = 0; j < needle.size(); j++){
                    if(needle[j] == haystack[i+j] && j == needle.size() - 1){
                        return i;
                    }
                    if(needle[j]!= haystack[i+j])break;
                }
            }
            return -1;
        }
    };
    

    relative point get√:

    hint :

  • 相关阅读:
    第一周学习进度
    四则运算
    添加课程
    继承和多态的动手动脑
    String 方法
    【CoreData】分页查询和模糊查询
    【CoreData】表之间的关联
    代码创建storyboard
    UIWindows&nbsp;使用注意
    UIApplicationDelegate
  • 原文地址:https://www.cnblogs.com/forPrometheus-jun/p/11063132.html
Copyright © 2011-2022 走看看