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 }
  • 相关阅读:
    Spring5源码分析之Bean生命周期
    关系图
    Spring5源码分析之AnnotationConfigApplicationContext
    Spring中好玩的注解和接口
    MyBatis使用总结
    设计模式的应用
    C#:网络传输问题
    工具软件:
    Rar安装包
    C#:注册组件 (cmd)
  • 原文地址:https://www.cnblogs.com/feiling/p/3216298.html
Copyright © 2011-2022 走看看