https://leetcode.com/PRoblems/implement-strstr/
算法思想:Implement strStr().Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
1)定義兩個(gè)Pointers:i和j,i初始化為指向haystack的的第一個(gè)元素;j初始化為指向needle的第一個(gè)元素
2)i的范圍是從0到兩個(gè)string的長度的差值,j的范圍是0到needle的長度;
3)判斷i指向的元素和j指向的元素(這里是j為0指向的,即第一個(gè)元素)是否相等,如果不等,i繼續(xù)向后移動(dòng);如果相等,就比較i后面的元素是否和j指向的所有元素是否相等,相等就返回這個(gè)i;如果不相等,i繼續(xù)向后移動(dòng)
程序代碼:public class Solution { public int strStr(String haystack, String needle) { int lenHay = haystack.length(); int lenNee = needle.length(); if (haystack == null || needle == null || lenHay < lenNee) { return -1; } if (needle.isEmpty()) { return 0; } int lenDiff = lenHay - lenNee; for (int i = 0; i <= lenDiff; i++) { if (haystack.charAt(i) == needle.charAt(0)) { int j = 1; while(j < lenNee) { if (haystack.charAt(i+j) != needle.charAt(j)) { break; } j++; } if (j == lenNee) { return i; } } } return -1; }}新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注