zoukankan      html  css  js  c++  java
  • 力扣题解 28th 实现 strStr()

    28th 实现 strStr()

    • 滑动窗口思想/简单模拟

      一个外循环用来遍历大串,一个内循环(或调substring函数)用来比对元素。

      class Solution {
          public int strStr(String haystack, String needle) {
              int l = needle.length(), n = haystack.length();
              for (int i = 0; i < n - l + 1; i++) {
                  if (haystack.substring(i, i + l).equals(needle)) {
                      return i;
                  }
              }
              return -1;
          }
      }
      
    • 双指针法

      上面的简单模拟需要进行很多优化,例如第一个字符就不同的情况下是不用进行下一步的。因此我们采用双指针法手动比对来剪枝优化。

      class Solution {
          public int strStr(String haystack, String needle) {
              int hl = haystack.length(), nl = needle.length();
              if (nl == 0) return 0;
      
              int i = 0, j = 0;
              while (i < hl) {
                  if (haystack.charAt(i) != needle.charAt(j)) {
                      i++;
                      continue;
                  }
                  int start_index = i;
                  while (i < hl && j < nl) {
                      if (haystack.charAt(i) == needle.charAt(j)) {
                          i++;
                          j++;
                      } else {
                          break;
                      }
                  }
                  if (i - start_index == nl) {
                      return start_index;
                  }
                  i = start_index + 1;
                  j = 0;
              }
      
              return -1;
          }
      }
      
  • 相关阅读:
    [leetCode]剑指 Offer 43. 1~n整数中1出现的次数
    [leetCode]剑指 Offer 42. 连续子数组的最大和
    HDU
    HDU
    HDU
    HDU
    HDU
    HDU
    POJ
    POJ
  • 原文地址:https://www.cnblogs.com/fromneptune/p/13253380.html
Copyright © 2011-2022 走看看