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

    Implement strStr().

    Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

    此题应用KMP算法来解,但忘记了,写了个普通解

    line 10: 当needle == "" 时, 返回haystack

    line 11: 循环终止条件需注意

     1 public class Solution {
     2     public static String strStr(String haystack, String needle) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         int needleLen = needle.length();
     6         int haystackLen = haystack.length();
     7         if (needleLen > haystackLen)
     8             return null;
     9 
    10         if (needleLen == 0)
    11             return haystack;
    12             
    13         int i = 0;
    14         for (; i < haystackLen - needleLen + 1;) {
    15             int j = 0;
    16             for (; j < needleLen;) {
    17                 if (needle.charAt(j) == haystack.charAt(i)) {
    18                     i++;
    19                     j++;
    20                 } else {
    21                     break;
    22                 }
    23             }
    24             if (j == needleLen) {
    25                 i = i - j;
    26                 return haystack.substring(i, haystackLen);
    27             } else {
    28                 i = i - j + 1;
    29             }
    30 
    31         }
    32 
    33         return null;
    34     }
    35 }
  • 相关阅读:
    图片延迟加载方法
    mongodb常用命令
    未知尺寸元素水平垂直居中:
    nodejs学习之加密
    nodejs学习之events的使用
    nodejs学习之events
    学习Nodejs之mysql
    PHP之几道面试题
    Jquery学习插件之手风琴
    我的第一篇博客
  • 原文地址:https://www.cnblogs.com/feiling/p/3210026.html
Copyright © 2011-2022 走看看