给定一个字符串,找出一个子串,拥有连续的字符且长度是最长的
例子:
给定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);
}
}