LeetCode第28题:实现strStr()
LeetCode第28题:实现strStr()
-
题目:给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。 解法一:第一想法是利用for循环,后来想起了双指针,就采用了双指针的方法。改了无数次,终于过了。。。
class Solution { public int strStr(String haystack, String needle) { if(haystack==null) return -1; int l1=haystack.length(); int l2=needle.length(); if(l1==0 && l2==0) return 0; if(l1!=0 && l2==0) return 0; if(l1<l2) return -1; int s1=0,s2=0,ans=-1; while(l1-s1>=l2-s2 && s2<l2){ if(haystack.charAt(s1)==needle.charAt(s2)){ ans=s1-l2+1; s1++; s2++; }else{ s1=s1-s2+1; s2=0; ans=-1; } if(s2==l2) return ans; } return ans; } }
-
解法二:解法中给出了KMP算法,勉强能理解,也记不住,不写了。。
上一篇:
IDEA上Java项目控制台中文乱码