给定一个字符串,找出一个子串,拥有连续的字符且长度是最长的
例子:
给定adddbcddddav
输出dddd
解法:
public class Test1 {
/*给出一个字符串,找出连续相同的最长的子串*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "adddbcddddav";
System.out.println(new Test1().solution(s));
}
public String solution(String s) {
if(s.length() <= 0)
return null;
else if(s.length() == 1) {
return s;
}
char current = s.charAt(0);//存储当前目标字符
int count = 1;//当前目标字符串的连续长度
int start_temp = 0,end_temp = 0;
int max = 0;//存储过往最长子串的长度
int start = 0,end = 0;//子串在源串的起始与结束位置
for(int i=1; i < s.length(); i++) {
if(s.charAt(i) == current) {
count++;
end_temp = i;
}else {
if(count > max) {
start = start_temp;
end = end_temp;
max = count;
}
start_temp = end_temp = i;
count = 1;
current = s.charAt(i);
}
}
return s.substring(start,end+1);
}
}
本文介绍了一种寻找字符串中最长连续相同字符子串的算法。通过遍历字符串,比较字符并更新最长子串的位置与长度,最终返回最长连续子串。此算法适用于文本处理、模式识别等场景。

9135

被折叠的 条评论
为什么被折叠?



