一、字符串匹配问题
string1 = “hellldwarld”
string2 = ‘ld’
判断string1中是否含有string2,如果存在返回第一个出现的位置,否则返回-1;
二、解决方案(模版)
1.暴力求解
public static int bfMethod(String str1, String str2) {
char[] chars1 = str1.toCharArray();
char[] chars2 = str2.toCharArray();
int s1Len = chars1.length;
int s2Len = chars2.length;
int i = 0; //指向S1
int j = 0; //指向S2
while (i < s1Len && j < s2Len) {
if (chars1[i] == chars2[j]) {
i++;
j++;
} else {
i = i - j + 1;
j = 0;
}
}
if (j == s2Len) {
return i - j;
} else
return -1;
}
2.kmp算法
// 写出搜索算法
public static int kmpSearch(String str1, String str2, int[] next) {
for (int i = 0, j = 0; i < str1.length(); i++) {
while (j > 0 && str1.charAt(i) != str2.charAt(j)) j = next[j - 1];
if (str1.charAt(i) == str2.charAt(j)) j++;
if (j == str2.length()) return i - j + 1;
}
return -1;
}
//获取到字串的部分匹配词 ,求去部分匹配值表
public static int[] kmpNext(String str) {
int[] next = new int[str.length()];
next[0] = 0; //如果字串str长度为1 那么部分匹配值一定为0
for (int i = 1, j = 0; i < str.length(); i++) {
while (j > 0 && str.charAt(i) != str.charAt(j)) j = next[j - 1];
if (str.charAt(i) == str.charAt(j)) j++;
next[i] = j;
}
return next;
}
推广
云数据库RDS MySQL 版是全球最受欢迎的开源数据库之一,作为开源软件组合 LAMP(Linux + Apache + MySQL + Perl/PHP/Python) 中的重要一环,广泛应用于各类应用场景。
点击查看->>> 云数据库新年钜惠,新用户1折起,爆款5-8折,MySQL 1年仅需19.9元.
云服务器ECS
云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的云计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。专业的售前技术支持,协助您选择最合适配置方案
点击查看->>> 弹性计算10年深厚技术积淀,技术领先、性能优异、 稳如磐石.
短信服务(Short Message Service)是广大企业客户快速触达手机用户所优选使用的通信能力。调用API或用群发助手,即可发送验证码、通知类和营销类短信;国内验证短信秒级触达,到达率最高可达99%;国际/港澳台短信覆盖200多个国家和地区,安全稳定,广受出海企业选用。
点击查看->>> 短信服务新用户 0元免费试用.