LeetCode 3. Longest Substring Without Repeating Characters--不包含重复字符的最长子串长度

来源:互联网 发布:owncloud php网盘源码 编辑:程序博客网 时间:2024/05/16 00:34

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.

package com.main;import java.util.HashMap;import java.util.Map;public class Main {    //两个指针,i在前,j在后,    //一开始没遇到重复元素时,i每次前进一次,j始终未0    //当后面每次遇到重复元素时,j指向前面重复元素的后一个位置,这样能保证i-j+1始终为最长的不重复子字符串的长度    public int lengthOfLongestSubstring(String s) {        Map<Character, Integer> map = new HashMap<Character, Integer>();        int max = 0;        Character c;        for (int i = 0, j = 0; i < s.length(); i++) {//i>=j始终成立            c = s.charAt(i);            if (map.containsKey(c)) {                j = Math.max(j, map.get(c) + 1);//j指针不能后退                //j = map.get(s.charAt(i))+1;如果是这样则对于“abba”字符串,在i指向最后一个‘a’时j会后退,会输出3则错误,正确为2            }            map.put(c, i);            max = Math.max(max, i - j + 1);        }        return max;    }    public static void main(String[] args) {        // write your code here        Main main = new Main();        int max = main.lengthOfLongestSubstring("abcab");//3        System.out.println(max);    }}

983 / 983 test cases passed.
Status: Accepted
Runtime: 51 ms
Your runtime beats 77.81 % of java submissions.
T(n) = O(n) 
T(n) = O(n) 






阅读全文
0 0
原创粉丝点击