【发布时间】:2020-12-25 01:24:32
【问题描述】:
我访问了多个网站,只是为了了解 String 类中使用的任何正则表达式函数的内部工作原理,例如 split() 和 replaceAll()。
我的代码:
String s = "abaaccasdraaaadsfd";
s = s.replaceAll("(.)\\1{1,}", "$17$1");
String[] s2 = s.split("7");
int len = 0;
for(String a : s2) {
if(a.length() > len) {
len = a.length();
}
}
System.out.println(len);
在线通用代码:
String s = "abaaccasdraaaadsfd";
int count=0;
int max=0;
for(int i=1;i<str.length();i++){
char ch =str.charAt(i-1);
char ch1=str.charAt(i);
if(ch!=ch1){
count++;
if(max<count){
max=count;
}
}else{
count=0;
}
}
System.out.println(max+1);
我想了解正则表达式是否在 O(n) 内部运行,其中 n 是字符串的长度,那么我的代码(使用正则表达式)在时间复杂度方面类似于一般在线代码(使用 for 循环)。
提前致谢。
【问题讨论】:
标签: java regex string time-complexity replaceall