leetcode第三题Longest Substring Without Repeating Characters

本文介绍了一种寻找字符串中最长无重复字符子串的算法实现。通过遍历字符串并利用列表来跟踪当前无重复字符的子串,该算法能够找到最长的无重复字符子串并返回其长度。

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given “abcabcbb”, the answer is “abc”, which the length is 3.

Given “bbbbb”, the answer is “b”, with the length of 1.

Given “pwwkew”, the answer is “wke”, with the length of 3. Note that the answer must be a substring, “pwke” is a subsequence and not a substring.
返回最大的没有重复的子字符串的长度,emmmm用的估计是最蠢的办法

public class Solution {

    //用了最蠢最暴力的方法,找出所有没有重复字符的子字符串,取最大的。
    public int lengthOfLongestSubstring(String s) {
        if("".equals(s)||s==null){
            return 0;
        }
        int current ;//用于记录当前的无重复字符的子字符串的length
        int result = 1;//用于记录最终结果的
        List nimahai = new ArrayList();
        nimahai.add(s.charAt(0));//list里面先把字符串的第一个加上
        for(int i =0;i<s.length()-1;i++){
            //搜寻所有没有重复字符的子字符串
          //如果第i+1个字符不是重复字符而且存储substring的list里面不包含i+1的字符则substring添加该字符,
            if (s.charAt(i+1)!=s.charAt(i) && !nimahai.contains(s.charAt(i+1))){
                nimahai.add(s.charAt(i+1));

                current = nimahai.size();
                result = Math.max(current,result);
            }
            //如果第i+1个字符是重复字符的话,定位到重复的字符,将重复字符以及前面的数值舍弃,
            else {
                List caonima = new ArrayList();
                caonima.addAll(nimahai);//保存当前list
                int index = nimahai.indexOf(s.charAt(i+1));//定位到重复字符
                nimahai.clear();//清空substringlist
                for (int j=index+1;j<caonima.size();j++){//重复字符后面的数值重新添加到substringlist
                    nimahai.add(caonima.get(j));

                }
                  nimahai.add(s.charAt(i+1));//因为重复的数值已经舍弃,所以第i+1的数值可以放入substringlist

            }
        }

        return result;


    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值