leetcode第三题Longest Substring Without Repeating Characters

来源:互联网 发布:mac删除系统文件 编辑:程序博客网 时间:2024/05/17 22:28

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;    }}
阅读全文
0 0