给定一个字符串,找出一个子串,拥有连续的字符且长度是最长的

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

}
    原文作者:RSMung
    原文地址: https://blog.csdn.net/lvdoujack/article/details/104941627
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞