java 实现 一个字符串中不重复最长子串
publicstaticvoidlongestNodupSubstring(Stringstring){intlen=string.length();if(len>0){...
public static void longestNodupSubstring(String string) {
int len = string.length();
if(len > 0){
Map<Character,Integer> cursor = new HashMap<Character,Integer>();
cursor.put(string.charAt(0),0);
int[] lengthAt = new int[string.length()];
lengthAt[0]=1;
int max = 0 ;
for(int i = 1 ; i < len;i++){
char c =string.charAt(i);
if(cursor.containsKey(c)){
lengthAt[i] = Math.min(lengthAt[i-1]+1, i-cursor.get(c));
}else {
lengthAt[i] = lengthAt[i-1]+1;
}
max = Math.max(max, lengthAt[i]);
cursor.put(c, i);
}
for(int i=0;i<len;i++){
if(max == lengthAt[i]){
System.out.println(string.substring(i-max+1, i+1));
}
}
}
}
}
不太理解lengthAt[i]和max的取值,能仔细讲讲这个程序的执行过程 展开
int len = string.length();
if(len > 0){
Map<Character,Integer> cursor = new HashMap<Character,Integer>();
cursor.put(string.charAt(0),0);
int[] lengthAt = new int[string.length()];
lengthAt[0]=1;
int max = 0 ;
for(int i = 1 ; i < len;i++){
char c =string.charAt(i);
if(cursor.containsKey(c)){
lengthAt[i] = Math.min(lengthAt[i-1]+1, i-cursor.get(c));
}else {
lengthAt[i] = lengthAt[i-1]+1;
}
max = Math.max(max, lengthAt[i]);
cursor.put(c, i);
}
for(int i=0;i<len;i++){
if(max == lengthAt[i]){
System.out.println(string.substring(i-max+1, i+1));
}
}
}
}
}
不太理解lengthAt[i]和max的取值,能仔细讲讲这个程序的执行过程 展开
展开全部
实现思路就是先拿第一个字符和第二个字符比较,不一样的话,取到这两个字符,之后和第三个比较,直到出现重复的保存下来(多次循环,取出最长的一个)。
public static void longestNodupSubstring(String string) {
int len = string.length();
if(len > 0){
Map<Character,Integer> cursor = new HashMap<Character,Integer>();
cursor.put(string.charAt(0),0);
int[] lengthAt = new int[string.length()];
lengthAt[0]=1;
int max = 0 ;
for(int i = 1 ; i < len;i++){
char c =string.charAt(i);
if(cursor.containsKey(c)){
lengthAt[i] = Math.min(lengthAt[i-1]+1, i-cursor.get(c));
}else {
lengthAt[i] = lengthAt[i-1]+1;
}
max = Math.max(max, lengthAt[i]);
cursor.put(c, i);
}
for(int i=0;i<len;i++){
if(max == lengthAt[i]){
System.out.println(string.substring(i-max+1, i+1));
}
}
}
}
}
public static void longestNodupSubstring(String string) {
int len = string.length();
if(len > 0){
Map<Character,Integer> cursor = new HashMap<Character,Integer>();
cursor.put(string.charAt(0),0);
int[] lengthAt = new int[string.length()];
lengthAt[0]=1;
int max = 0 ;
for(int i = 1 ; i < len;i++){
char c =string.charAt(i);
if(cursor.containsKey(c)){
lengthAt[i] = Math.min(lengthAt[i-1]+1, i-cursor.get(c));
}else {
lengthAt[i] = lengthAt[i-1]+1;
}
max = Math.max(max, lengthAt[i]);
cursor.put(c, i);
}
for(int i=0;i<len;i++){
if(max == lengthAt[i]){
System.out.println(string.substring(i-max+1, i+1));
}
}
}
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询