Implement strStr()
题目地址:
https://leetcode.com/problems/implement-strstr/#/description
题目:
解题思路:
常规思路就是先找到第一个相同的char,然后y比较之后的每个char。
代码:
https://leetcode.com/problems/implement-strstr/#/description
题目:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
解题思路:
常规思路就是先找到第一个相同的char,然后y比较之后的每个char。
代码:
public int strStr(String haystack, String needle) { if(haystack == null || needle == null){ return -1; } int len1 = haystack.length(); int len2 = needle.length(); for(int i = 0; i <= len1 - len2; i++){ int j = 0; while(j <= len2 - 1 && haystack.charAt(i + j) == needle.charAt(j)){ j++; } if(j == len2){ return i; } } return -1; }

Comments
Post a Comment