欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

一、字符串问题

发布时间:2023/12/20 54 豆豆
生活随笔 收集整理的这篇文章主要介绍了 一、字符串问题 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

 

题目:对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1。

分析:命名有意义;正常的for循环即可;一定有非空检查;数组不要越界

1)常规算法:

2,not ac :循环条件不对,j在循环内定义,判断i+ j,返回值cuo ,

robinhap not ac :target长度没判断,31 ^,长度选错,循环变量错,targethash算错,targetHash = targetHash * 31 % BASE + target.charAt(i) % BASE;没double check

class Solution {/*** Returns a index to the first occurrence of target in source,* or -1 if target is not part of source.* @param source string to be scanned.* @param target string containing the sequence of characters to match.*/public int strStr(String source, String target) {// write your code here//非空检查if (source == null || target == null) {return -1;}for (int i = 0; i < source.length() - target.length() + 1; i++) {int j = 0;for (j = 0; j < target.length(); j++) {if (source.charAt(i + j) != target.charAt(j)) {break;}}// loop overif (j == target.length()) {return i;}}return -1;} } View Code

 

2)Rabin-Karp算法:利用hash表的原理,把字符串转为数字。最后通过比较hash值是否相同

思路:
base
1、异常检测
2、target长度,为空检测
3、计算31^m(power):边乘边模
4、targethash: 边乘边加边模
5、hashcode :边乘边加边模
i < mi-1:继续
i>m-1:abcd - a ,负数检测
hashcode == targethash
double check

not ac : abcd -a ,hashCode = hashCode - source.charAt(i - m) * power % BASE;忘记模;判断hashcode 是否小于0,写在外面了

class Solution {/*** Returns a index to the first occurrence of target in source,* or -1 if target is not part of source.* @param source string to be scanned.* @param target string containing the sequence of characters to match.*/public int BASE = 1000000;public int strStr(String source, String target) {// write your code here//非空检查if (source == null || target == null) {return -1;}int m = target.length();//target长度检查if (m <= 0) {return 0;}//31^mint pow = 1;for (int i = 0; i < m; i++) {pow = pow * 31 % BASE;}//targetcodeint targetCode = 0;for (int i = 0; i < m; i++) {targetCode = (targetCode * 31 + target.charAt(i)) % BASE;}//hashCodeint hashCode = 0;for (int i = 0; i < source.length(); i++) {hashCode = (hashCode * 31 + source.charAt(i)) % BASE;if (i < m - 1) {continue;}// i// abcd - aif (i >= m) {hashCode = hashCode - (pow * source.charAt(i - m)) % BASE;}// hashcode < 0 ?if (hashCode < 0) {hashCode = hashCode + BASE;}//hash值是否相等if (hashCode == targetCode) {//double checkif (source.substring(i - m + 1, i + 1).equals(target)) {return i - m + 1;}}}return -1;} } View Code

 

转载于:https://www.cnblogs.com/lingli-meng/p/6511499.html

创作挑战赛新人创作奖励来咯,坚持创作打卡瓜分现金大奖

总结

以上是生活随笔为你收集整理的一、字符串问题的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。