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

    Implement strStr().

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

     此题的想法是遍历一遍haystack数组,当遍历到cur的元素和needle第一个char一样的时候,看haystack的子字符串是否和needle,代码如下:

     1 public class Solution {
     2     public int strStr(String haystack, String needle) {
     3         int len = haystack.length();
     4         int index = -1;
     5         if(needle.length()==0) return 0;
     6         if(haystack.length()==0) return index;
     7         for(int i=0;i<len;i++){
     8             if(haystack.charAt(i)==needle.charAt(0)){
     9                 if(ismatch(haystack,needle,i)){
    10                     index = i;
    11                     break;
    12                 }
    13             }
    14         }
    15         return index;
    16     }
    17     public boolean ismatch(String haystack,String needle,int i){
    18         int k = 0;
    19         while(k<needle.length()&&(k+i)<haystack.length()&&haystack.charAt(i+k)==needle.charAt(k)){
    20             k++;
    21         }
    22         if(k==needle.length()) return true;
    23         return false;
    24     }
    25 }

     本题也可以使用kmp的做法来做,希望第三遍刷的时候能掌握。

     
  • 相关阅读:
    HAOI2008题解
    codeforces round375(div.2)题解
    codeforces round373(div.2) 题解
    TJOI2015题解
    CF976D. Degree Set
    dtoj#4243. 熊猫(i)
    dtoj#4242. 大爷(w)&&CF1061E
    CF786C Till I Collapse
    dtoj#4239. 删边(cip)
    dtoj#2504. ZCC loves cube(cube)
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6388620.html
Copyright © 2011-2022 走看看