(java)leetcode-28

    xiaoxiao2021-04-04  36

    Implement strStr()

    Implement strStr().

    Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

    解题思路:

    这道题还是比较简答的,就是找到字符串的子串,匹配的话就返回第一个匹配值所在的index,不匹配的话就返回-1。类似与string中的indexOf方法。

    [java] view plain copy print ? public class Solution {      public int strStr(String haystack, String needle) {          int len_needle = needle.length();          int len_haystack = haystack.length();          int n1 = 0;          int h1 = 0;          while(h1+len_needle<=len_haystack)          {              int k = h1;              while(n1<len_needle && haystack.charAt(k) == needle.charAt(n1))              {                  n1++;                  k++;              }              if(n1 == len_needle)                  return h1;              n1 = 0;              h1++;          }          return -1;      }  }   public class Solution { public int strStr(String haystack, String needle) { int len_needle = needle.length(); int len_haystack = haystack.length(); int n1 = 0; int h1 = 0; while(h1+len_needle<=len_haystack) { int k = h1; while(n1<len_needle && haystack.charAt(k) == needle.charAt(n1)) { n1++; k++; } if(n1 == len_needle) return h1; n1 = 0; h1++; } return -1; } }

    转载请注明原文地址: https://ju.6miu.com/read-666146.html

    最新回复(0)