zoukankan      html  css  js  c++  java
  • [leetcode]28. Implement strStr()实现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
    

    Clarification:

    What should we return when needle is an empty string? This is a great question to ask during an interview.

    题意:

    实现strStr() : Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1.

    Solution1:Two Pointers, finding substring[i...j] in str1,such that it equals str2

    code:

     1 /*
     2 Time: O(n^2). 
     3 Space: O(1).
     4 */
     5 
     6 class Solution {
     7     public int strStr(String s1, String s2) {
     8         //题意确认 return 0 when needle is an empty string
     9         if(s2.length() == 0) return 0;
    10         
    11         //for(int i = 0; i < s1.length(); i++){ 确保s1中含有s2,则扫s1的指针的范围可以缩小到s1.length() - s2.length() + 1
    12         for(int i = 0; i < s1.length() - s2.length() + 1; i++){
    13             int j = i; 
    14             int k = 0; 
    15             while( j < s1.length() && k < s2.length() && s1.charAt(j) == s2.charAt(k)){
    16                 j++;
    17                 k++;
    18             }
    19             if( k == s2.length()){
    20                 return i;
    21             } 
    22         }   
    23         return -1;
    24     }    
    25 }
  • 相关阅读:
    java数组
    java 常用类
    java 集合(一)
    mysql相关操作(一)
    记录java BigDecimal
    hxg-yw
    一个困惑我好久的问题
    关于重载和重写的一些小知识
    几个常用的HTTP状态码
    死锁产生的原因和条件简述
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10674671.html
Copyright © 2011-2022 走看看