This is my answer in Java, plz tell me where could I improve to reduce time. Txs


  • 1
    S

    public class Solution {

    public int lengthOfLongestSubstring(String s) {
    	int max = 0, i = 0, j = 0;
    	Map<String, Integer> map = new HashMap<String, Integer>();
    	while (j < s.length()) {
    		String st = s.substring(j, j + 1);
    		if (map.containsKey(st) && map.get(st) >= i)
    			i = map.get(st) + 1;
    		map.put(st, j++);
    		max = max > (j - i) ? max : (j - i);
    	}
    	return max;
    }
    

    }


  • 4
    C
    1. use a 256 size array instead of map
    2. don't use substring, just use charAt if you are using java

  • 0
    S

    Great!! I successfully shorten the running time from 8ms to 5ms, and beat 92% users!
    really appreciate for your sharing!


  • 0
    T

    Nice one, store the index of the last occurrence instead of just the existence of a last occurrence!


  • 0
    S

    Why size 256 array instead of 128 (0 through 127 being possible ASCII values) ?


  • 0
    Y

    why input 'acdcd' the result is 3 ???


  • 0
    S

    ???????????????? or else?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.