[LeetCode]-algorithms-Longest Substring Without Repeating Characters
Posted 练子
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode]-algorithms-Longest Substring Without Repeating Characters相关的知识,希望对你有一定的参考价值。
Given a string, find the length of the longest substring without repeating characters. For example,
the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3.
For "bbbbb" the longest substring is "b", with the length of 1.
分析:求最大不重复子串的长度
public int lengthOfLongestSubstring(String s) { char[] arr = s.toCharArray(); HashMap<Character,Integer> map = new HashMap<Character,Integer>(); int len = 0; for(int i=0; i<arr.length; i++){ if(map.containsKey(arr[i])){ len = Math.max(len, map.size()); i = map.get(arr[i]); map.clear(); }else{ map.put(arr[i],i); } } len = Math.max(len, map.size()); return len; }
结语:依次把字符串的每个字符以及它对应的下表索引存入到Map中,字符为键,下表索引为值
每插入一次,进行判断,如果存在则从这个重复的字符的下一个开始遍历
以上是关于[LeetCode]-algorithms-Longest Substring Without Repeating Characters的主要内容,如果未能解决你的问题,请参考以下文章