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
    拿到题目,返回下标???直接String.indexOf()就可以了啊,于是就试了一下,于是就过了?还99.9%?看了一下别人的,题目的用意应该是想用比较的方法来实现这个indexOf方法。
    strStr这个方法是c++里面的,所以一看到这个题目以为只要返回就好了,对于java来说应该改成implement String.indexOf()方法。还是上代码吧。
    public static int strStr(String haystack, String needle) {
            return haystack.indexOf(needle);
        }

    别人的:

    public int strStr(String haystack, String needle) {
      for (int i = 0; ; i++) {
        for (int j = 0; ; j++) {
          if (j == needle.length()) return i;
          if (i + j == haystack.length()) return -1;
          if (needle.charAt(j) != haystack.charAt(i + j)) break;
        }
      }
    }
  • 相关阅读:
    Python人工智能之路
    Flask最强攻略
    Flask最强攻略
    Flask最强攻略
    Flask最强攻略
    Flask最强攻略
    Flask最强攻略
    Flask最强攻略
    Flask最强攻略
    Flask最强攻略
  • 原文地址:https://www.cnblogs.com/GoForMyDream/p/8580597.html
Copyright © 2011-2022 走看看