leetcode第三题
leetcode第三题:
题目:
给定一个字符串,找出不含有重复字符的最长子串的长度。
源码(使用java语言):
class Solution {
    public int lengthOfLongestSubstring(String s) {
        int result = 0;
        int front = 0 ;
        int after = 0;
        char[] temp = s.toCharArray();//save the String to a chararray
        Map<Character,Integer> map = new HashMap<>();
        while(after<temp.length&&front<temp.length){
            if(map.containsKey(temp[after])){
                if(front<map.get(temp[after])+1){
                    front = map.get(temp[after])+1;    
                }    
            }
            map.put(temp[after],after);
            after++;
            if(after - front >result){
                result = after -front;
            }
        }
     return result;   
    }
}
用时64ms
算法亮点,利用map键值对以及游标来巧妙获取最长子串长度,且仅需遍历一遍
因为map的containskey在查询到一个相同的值是就返回true,所以二层嵌套的if语句要加上front<map.get(temp[after])以保证front游标一直向前浮动
以上
                    
                
                
            
        
浙公网安备 33010602011771号