• [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 }
  • 相关阅读:
    yum install mysql.i686
    firefox无法浏览flash的解决方案
    vb.net如何打开指定文件
    XML文件操作的简单类
    window server 安装与卸载
    常用的sql语句
    with进行递归表
    常用js
    调用Google的自动翻译
    MySQl 总结知识
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10674671.html
Copyright © 2020-2023  润新知