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

      这道题事实上就是编译一个String.indexOf()的函数,所以这道题直接用s1.indexOf(s2)便可解。但是这样做没有什么意义, 所以我们还是老老实实的一个一个遍历,当碰到首字母相同的时候,就判断加下来的字符串和needle是否相同,如果不相同,继续遍历。

      代码如下:

     1 public class Solution {
     2     public int strStr(String haystack, String needle) {
     3         if (needle.length() == 0) return 0;
     4         for (int i = 0; i < haystack.length() - needle.length() + 1; i++) {
     5             //如果首字母相同,check接下来needle长度的字符串是否和needle相同。
     6             if (haystack.charAt(i) == needle.charAt(0)) {
     7                 if (checkStr(haystack,i,needle)) return i;
     8             }
     9         }
    10         return -1;
    11     }
    12     
    13     private boolean checkStr(String haystack, int index, String needle) {
    14         int needleIndex = 0;
    15         while (needleIndex < needle.length()) {
    16             if (haystack.charAt(index) != needle.charAt(needleIndex)) return false;
    17             else {
    18                 index++;
    19                 needleIndex++;
    20             }
    21         }
    22         return true;
    23     }
    24 }
  • 相关阅读:
    time模块
    日期和时间
    异常和函数
    finally子句
    自定义异常
    异常中的else
    全捕捉
    排序算法---希尔排序
    排序算法---直接插入排序
    排序算法---快速排序
  • 原文地址:https://www.cnblogs.com/kepuCS/p/5282923.html
Copyright © 2011-2022 走看看