leetcode 003 Longest Substring Without Repeating Characters(java)

来源:互联网 发布:java web开发实战经典 编辑:程序博客网 时间:2024/05/22 03:43

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));        }    }}


0 0
原创粉丝点击