作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
问题很简单,不用 String.split("ABC") 在 "ABCDSGDABCSAGAABCCCCAAABAABC"中找到 "ABC"
这是我提出的解决方案,我正在寻找可能比这个更好的解决方案。
public static void main(String[] args) {
String haystack = "ABCDSGDABCSAGAABCCCCAAABAABC";
String needle = "ABC";
char [] needl = needle.toCharArray();
int needleLen = needle.length();
int found=0;
char hay[] = haystack.toCharArray();
int index =0;
int chMatched =0;
for (int i=0; i<hay.length; i++){
if (index >= needleLen || chMatched==0)
index=0;
System.out.print("\nchar-->"+hay[i] + ", with->"+needl[index]);
if(hay[i] == needl[index]){
chMatched++;
System.out.println(", matched");
}else {
chMatched=0;
index=0;
if(hay[i] == needl[index]){
chMatched++;
System.out.print("\nchar->"+hay[i] + ", with->"+needl[index]);
System.out.print(", matched");
}else
continue;
}
if(chMatched == needleLen){
found++;
System.out.println("found. Total ->"+found);
}
index++;
}
System.out.println("Result Found-->"+found);
}
创建这个我花了一段时间。有人可以提出更好的解决方案(如果有的话)附言如果您觉得系统输出很乱,请将其删除。
最佳答案
怎么样:
boolean found = haystack.indexOf("ABC") >= 0;
**编辑 - 该问题询问出现的次数,因此这是上述内容的修改版本:
public static void main(String[] args)
{
String needle = "ABC";
String haystack = "ABCDSGDABCSAGAABCCCCAAABAABC";
int numberOfOccurences = 0;
int index = haystack.indexOf(needle);
while (index != -1)
{
numberOfOccurences++;
haystack = haystack.substring(index+needle.length());
index = haystack.indexOf(needle);
}
System.out.println("" + numberOfOccurences);
}
关于java - 最优化地计算 Haystack 字符串中针字符串的出现次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2515858/
假设我有一个显示用户信息(主要是姓名和年龄)的网站,我想知道从数据库中获取所有记录的最优化和最有效的方法是什么。 虽然我刚刚开始学习 DBMS,但这是我的第一段代码 connect_error
在我的应用程序中,我需要创建一个带有 1px 彩色边框和圆角半径的按钮。宽度可能不同。 当然我会创建一个 UIButton 设置它的 layer.cornerRadius 和 layer.border
我是一名优秀的程序员,十分优秀!