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

    题目描述:

    Implement strStr().

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

    Example 1:

    Input: haystack = "hello", needle = "ll"
    Output: 2

    Example 2:

    Input: haystack = "aaaaa", needle = "bba"
    Output: -1

     

    要完成的函数:

    int strStr(string haystack, string needle)
     

    代码:

    int strStr(string haystack, string needle) 
        {
            if(needle.size()==0&&haystack.size()!=0)
                return 0;
            else if(needle.size()!=0&&haystack.size()==0)
                return -1;
            else if(needle.size()==0&&haystack.size()==0)
                return 0;
            else
            {
                int changdu=haystack.size()-needle.size();
                for(int i=0;i<=changdu;i++)
                {
                    if(haystack.substr(i,needle.size())==needle)
                    return i;
                }
                return -1;
            }
            
        }

    注意事项:

    1、边界情况的判定。haystack为空?needle为空?haystack比needle长度小?
     
    2、haystack.substr(x,y),x为起始点index,y为长度,注意不可以让x和y超过haystack的限制。
     
    3、string的size不是int类型,估计为unsigned类型。比如haystack="",needle="a",当cout<<haystack.size()-needle.size()<<endl;的时候,得到的会是一堆乱码,这时候强制类型转换,cout<<int(haystack.size()-needle.size())<<endl;才会得到-1的结果,这点在//**那里体现出来了。笔者在第一次submit的时候也犯了这个错误。

     

  • 相关阅读:
    java实现微信红包分配算法
    认识J2SE
    java设计模式(2)
    java设计模式(1)
    模拟做饭系统(java+线程中的join方法)
    学习接水系统(java+thread线程)
    1. linux系统简介
    Codeforces Round #350 (Div. 2)解题报告
    2014蓝桥杯决赛解题报告
    末学者笔记--Python函数一玄
  • 原文地址:https://www.cnblogs.com/chenjx85/p/8708997.html
Copyright © 2011-2022 走看看