字符串匹配问题是很经典的问题,在此详细记录一下各种方法。(Java实现)LeetCode28
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
一,暴力
//1.substring
class Solution { public int strStr(String haystack, String needle) { int h = haystack.length(); int n = needle.length(); for (int i = 0; i <= h - n; i++) { if (haystack.substring(i, i + n).equals(needle)) return i; } return -1; } }
//2.indexOf
public int strStr(String haystack, String needle) {
return haystack.indexOf(needle);
}
/**
indexOf源码:(找到首字母后双指针)
*/
//先在source中找到首字母与target相同的index。再用双指针判定,如果指到末尾则完全匹配,返回索引,
//否则回溯source下一个字符。(只保留重要部分)
static int indexOf(char[] source, int sourceOffset, int sourceCount, char[] target, int targetOffset, int targetCount, int fromIndex) {char first = target[targetOffset]; int max = sourceOffset + (sourceCount - targetCount); for (int i = sourceOffset + fromIndex; i <= max; i++) { /* Look for first character. */ if (source[i] != first) { while (++i <= max && source[i] != first); } /* Found first character, now look at the rest of v2 */ if (i <= max) { int j = i + 1; int end = j + targetCount - 1; for (int k = targetOffset + 1; j < end && source[j] == target[k]; j++, k++); if (j == end) { /* Found whole string. */ return i - sourceOffset; } } } return -1; }
二,
t
原文:https://www.cnblogs.com/faded828x/p/13156549.html