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 }
  • 相关阅读:
    mac 快捷键
    mac 配置nginx 虚拟域名(转载)
    StringUtils中 isNotEmpty 和isNotBlank的区别【java字符串判空】
    软件常用版本英文snapshot和ga
    IF条件控制
    函数与方法
    数据类型
    函数 FUNCTION
    集合 SET
    字典 DICTIONARY
  • 原文地址:https://www.cnblogs.com/feiling/p/3216298.html
Copyright © 2011-2022 走看看