题目:力扣https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
public class Solution {
public int lengthOfLongestSubstring(String s){
int count=1;
if(s.length()==0){
count = 0;
}else if(s.length()==1){
count = 1;
}else{
int temp=1;
for(int i=1;i<s.length()+1;i++){
temp = 0;//临时记录
for(int j=i-1;j>-1;j--){
String str = s.substring(j,i);
boolean check = checkDifferent(str);
if(check){
temp = temp+1;
}else{
break;
}
}
if(temp>count){
count = temp;
}
}
}
return count;
}
public static boolean checkDifferent(String src) {
//用来标记的数组
int[] temp = new int[128];
for (int i = 0;i<src.length();i++) {
//对号入座
int c = (int)(src.charAt(i));
if (temp[c]>0)return false;
else temp[c]++;
}
return true;
}
}
(这算法确实拉胯了些,但不管怎样还是跑成功了...凑合着先吧,以后有机会再优化甚至重写)
思路:编写一个“查重”(checkDifferent)的方法,为后续做准备。对不同的字符长度分类讨论,并作一定的处理。若字符串长度大于或等于2时,采取下述思想进行查重。
{例如先有一串字符串——“abcabb”,i先处于1的位置,j处于i-1即0的位置,然后取出(0,1)的字符串,调用checkDifferent查重方法,查重通过则temp的值加1,若出现重复则跳出该循环,将temp与count比大小,若temp大则用temp的值取代原count的值。然后重置temp的值为1,i往后移一位即处于2的位置。j则在1的位置往前遍历,直至到达0的位置或者查找到相同的元素时停止,此时会有一个新的temp,再次与count比大小,依旧取较大值作为count的值。以此类推,知道i达到6的位置,遍历比较完得到的count就是无重复字符的最大子串。还是看视频比较生动易懂一些...}
leetcode3无重复字符最长子串 解题思路
1.写“查重”方法checkDifferent()。这是一个Boolean类型的方法,java.lang.String.charAt()方法 返回 指定索引 处的 char值。若找到相同的字符则返回false,反之,则返回true值。
public static boolean checkDifferent(String src) {
//用来标记的数组
int[] temp = new int[128];
for (int i = 0;i<src.length();i++) {
//对号入座
int c = (int)(src.charAt(i));
if (temp[c]>0)return false;
else temp[c]++;
}
return true;
}
2.对字符长各种长度进行分类讨论。若入参的字符串长度为0,那么无重复的最长子串不需要经过判断也可知其为0。同理可得,入参的字符串长度为1时,它的无重复最长子串长度也为1。
public int lengthOfLongestSubstring(String s){
int count=1;
if(s.length()==0){
count = 0;
}else if(s.length()==1){
count = 1;
}else{
//......(未写)
}
//......(未写)
}
3.若入参的字符串的长度大于或者等于2,则按照上述视频的思路进行一一查重。每一轮遍历查重都会得出一个新的temp值,若此temp值较于count值大,则将temp的值赋予count值。
int temp=1;
for(int i=1;i<s.length()+1;i++){
temp = 0;//临时记录
for(int j=i-1;j>-1;j--){
String str = s.substring(j,i);
boolean check = checkDifferent(str);
if(check){
temp = temp+1;
}else{
break;
}
}
if(temp>count){
count = temp;
}
}
4.最后返回count即可。
return count;