题目描述
请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。假设字符串中只包含从’a’到’z’的字符。例如,在字符串中”arabcacfr”,最长非重复子字符串为”acfr”,长度为4。
解题思路
老老实实O(n^2)实现,细节你懂的,书上那种高效率的我没太看懂。要啥自行车…
算法图解
比较简单不做图了!就是拿出每一位组成串,判断新入字符的是否存在,如果存在一切归零。从下一位开始循环往复知道最后。
参考代码:
package offer
;
public class Offer48 {
public static void main(String
[] args
) {
String s
= "arabcacfropi";
System
.out
.println(lengthOfLongestSubstring(s
));
}
public static int lengthOfLongestSubstring(String s
) {
int length
= s
.length();
int maxlength
= 0;
int currentlength
= 1;
char[] chars
= s
.toCharArray();
StringBuilder temp
= new StringBuilder();
for (int i
= 0; i
< length
; i
++) {
temp
= temp
.append(chars
[i
]);
for (int j
= i
+ 1; j
< length
; j
++) {
if (temp
.indexOf(chars
[j
] + "") != -1) {
if (currentlength
>= maxlength
) {
maxlength
= currentlength
;
}
temp
.delete(0, length
);
currentlength
=1;
break;
} else {
temp
.append(chars
[j
]);
currentlength
++;
}
}
}
return maxlength
;
}
}
附录
该题源码在我的 ?Github 上面!