leetcode 003 Longest Substring Without Repeating Characters(java)

Longest Substring Without Repeating Characters

My Submissions
Total Accepted: 111400 Total Submissions: 532861 Difficulty: Medium

 

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.

 

题意:求最长连续不重复子序列,和字典序没关系!!!!不能习惯leetcode测试数据给的太少,刚开始把题意理解错了。哎,英文太烂。

用HashMap很好解。出现重复的字母更新一下start就好。

 

import java.util.HashMap;
import java.util.Scanner;


public class Solution {
    public static int lengthOfLongestSubstring(String s) {
        int ans=0;
        int start=0;
        int i=0;
        HashMap<Character, Integer> map=new HashMap<Character, Integer>();
        
        for(i=0;i<s.length();i++){
            char c=s.charAt(i);
            if(map.containsKey(c)&&start<=map.get(c)){
                ans=Math.max(ans, i-start);
                start=map.get(c)+1;
                map.put(c, i);
            }
            else{
                map.put(c, i);
            }
            
        }
        return Math.max(ans, i-start);
    }  
    
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        while(true){
            String tmp=scanner.next();
            System.out.println(lengthOfLongestSubstring(tmp));
        }
    }
}

 

posted on 2015-12-09 22:55  ArcherCheng  阅读(125)  评论(0编辑  收藏  举报