[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.
LeetCode水题,无聊水一发,题目是求最长不重复字符的子字符串.
Ok,that's right.
简单分析下:
1.当不发生重复字符出现时,直接加入到集合.
2.当发生重复字符的时候,先记录下当前集合的长度,取current.size() > maxLength;maxLength = current.size(),然后要把发生重复的字符前面的序列去掉,并且吧新的字符加入到集合.
(exp:cdvdfa,当道第二个d时,需要把cd去掉,形成vdfa序列即可).
3.重复1 2.
JAVA CODE:
public int lengthOfLongestSubstring( String s ) { int maxLength = 0; List<Character> exist = new ArrayList<Character>(); for( int i = 0; i < s.length(); i++ ) { if( !exist.contains( s.charAt( i ) ) ) { exist.add( s.charAt( i ) ); } else { if( exist.size() > maxLength ) { maxLength = exist.size(); } while( !exist.isEmpty() && exist.get( 0 ) != s.charAt( i ) ) { exist.remove( 0 ); } exist.remove( 0 ); exist.add( s.charAt( i ) ); } } if( exist.size() > maxLength ) maxLength = exist.size(); return maxLength; }