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

    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

    笨方法1:
    class Solution {
        public int strStr(String haystack, String needle) {
           if(needle==""||needle==null){
               return 0;
           } 
           else return haystack.indexOf(needle);
        }
    }
    

      直接用indexOf

    方法2:

    class Solution {
        public int strStr(String haystack, String needle) {
        if (needle.isEmpty()) return 0;
        int m = haystack.length();
        int n = needle.length();
        if (n > m) return -1;
        for (int i = 0; i <= m - n; i++) {
            int j = 0;
            for (; j < n; j++) {
                if (haystack.charAt(i + j) != needle.charAt(j)) break;
            }
            if (j == n) return i;
        }
        return -1; 
        }
    }
    
    
  • 相关阅读:
    python基本数据类型剖析
    常用正则表达式
    python_re模块
    迭代器模式
    状态模式
    备忘录模式
    asp.net 发送邮件
    建造者模式
    抽象工厂模式
    摸板模式与钩子
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10153583.html
Copyright © 2011-2022 走看看