leetcode - 3、Longest Substring Without Repeating Characters

题目链接:https://leetcode.com/problems/longest-substring-without-repeating-characters/description/

题目要求:求出最长的不重复子串

思路:

1、采用map,遍历字符串,将每个字符put进map
2、如果长度为1,直接输出1
3、end-begin+1(注意+1)
end为当前遍历到的位置,
begin为重复位置+1
4、在遍历字符串的时候,判断当前字符是否存在resultMap.containsKey(key),
如果不存在,将其put进map,并维护end-begin+1
如果存在,重置begin位置,计算长度
(begin的位置判断:如果当前begin位置index比重复位置大,需要begin==当前begin位置index,否则等于重复位置)
begin = begin > (resultMap.get(key)+1) ? begin : (resultMap.get(key)+1)
长度维护:
result = result > (end-begin+1) ? result : (end-begin+1);

 

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        char str[] = s.toCharArray();
        int len = str.length;
        if(len == 1 ){
            return 1;
        }else {
            //        int sum = 0;
            int result = 0;
            int begin = 0;
            int end = 0;
            Map<String,Integer> resultMap = new HashMap<String, Integer>();
            for(int i = 0; i<len; i++){
                String key = str[i]+"";
                end = i;
                //未重复
                if(!resultMap.containsKey(key)){
                    resultMap.put(key,i);
                    result = result > (end-begin+1) ? result : (end-begin+1);
                }else { //遇到重复
//                resultMap.clear();
                    begin = begin > (resultMap.get(key)+1) ? begin : (resultMap.get(key)+1);
                    result = result > (end-begin+1) ? result : (end-begin+1);
                    resultMap.put(key,i);
                }
            }
//            System.out.println(result);
            return result;
        }
    }
}

  

posted @ 2018-09-17 11:28  非我非非我  阅读(108)  评论(0编辑  收藏  举报