gpt4 book ai didi

java - 检查字符串中是否存在模式

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:45:43 25 4
gpt4 key购买 nike

我想使用迭代检查字符串中是否存在某种模式。

这是我目前所拥有的,但因此我不断出错。

public static void main(String args[]) {
String pattern = "abc";
String letters = "abcdef";

char[] patternArray = pattern.toCharArray();
char[] lettersArray = letters.toCharArray();

for(int i = patternArray.length - 1; i<= 2; i++){
for(int j = lettersArray.length - 1; j <= 5;j++){
if(patternArray[i] == lettersArray[j]){
System.out.println("true");
} else{
System.out.println("false");
}
}
}
}

基本上我想检查字符串 abcdef 中是否存在 abc

注意:我不想使用正则表达式,因为它太简单了。我试图在没有它的情况下找到解决方案,因为我很好奇如何通过迭代来做到这一点。

最佳答案

这是一个朴素的字符串匹配程序,它将找到模式的所有匹配项。

因为 O(mn) 的时间复杂度(m 和 n 分别是搜索字符串和模式的长度),不推荐用于任何实用的东西。

class Potato 
{
public static void main(String args[])
{
char[] search = "flow flow flow over me".toCharArray();
char[] pattern = "flow".toCharArray();

for(int i = 0; i <= search.length - pattern.length; i++)
// `-` don't go till the end of the search str. and overflow
{
boolean flag = true;
for(int j=0; j < pattern.length; j++)
{
if(search[i + j] != pattern[j])
{
flag = false;
break;
}
}
if (flag)
System.out.println("Match found at " + i);

}
}
}

关于java - 检查字符串中是否存在模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33884808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com