java - 如何将while循环转换为for循环
问题描述
我正在使用java研究字符串匹配算法,我需要将while循环转换为for循环以便轻松处理它。
KMPSearch 中的 while 循环我需要转换为 for 循环,目的是在搜索过程开始之前检查要跳过的某些字符。我不知道在哪里插入这部分代码
void KMPSearch(String txt, String pat) {
int N=txt.length();
int M=pat.length();
int lps[]=new int[M];
int j=0;// index of patt
int i=0; //index of txt
int c=0;
computeLPS(lps,M,pat);
//char [] skipChar=new char[] {'s','d','a','c'};
while(i<N) {
if(pat.charAt(j)==txt.charAt(i)) {
i++;
j++;
}
if(j==M) {
System.out.println("pattern found at index "+ (i-j-c));
j=lps[j-1];
}
else if (i<N && pat.charAt(j) != txt.charAt(i)) {
if (j != 0) {
j=lps[j-1];
}
else {
i=i+1;
}
}
}
}
解决方案
如果我理解正确,您需要一个循环,该循环在txt
. 您的循环可以这样重写:
for (int i = 0; i < N; i++) {
char ch = txt.charAt(i);
/* Perform your potential char test here */
while (j > 0 && (j == M || pat.charAt(j) != ch)) {
if (j == M) {
System.out.println("pattern found at index "+ (i-j-c));
}
j = lps[j-1];
}
if (pat.charAt(j) == ch) {
j++;
}
}
它并不完全相同,因为理论上您的循环可以j == M
在新迭代开始时进行迭代——这会导致错误。发生这种情况时,上述替代方案将继续内部 while 循环。但可能你lps
的代码也永远不会遇到这种情况。所以它们实际上是等价的。
推荐阅读
- c# - 从插件中找不到视图“索引”
- object - Blender : Some objects disappear when I turn to camera mode (it's not the snapping I think)
- php - PHP获取上层A Tag href链接的IMG Tag?
- javascript - 渲染对象数组 React
- javascript - React animate fade-in and fade-out with CSSTransitionGroup on conditionally rendered component
- javascript - Radio - 选中时在 div 中添加类
- java - How can I save and get a image from my database
- python - 将扫描路径绘制到图像上
- java - Throwable 类曾经是抽象的吗?
- javascript - 使用 JQuery .load() 函数后 Javascript 不起作用