LeetCode – Longest Substring Without Repeating Characters (Java)

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.

Java Solution 1

The first solution is like the problem of "determine if a string has all unique characters" in CC 150. We can use a flag array to track the existing characters for the longest substring without repeating characters.

public int lengthOfLongestSubstring(String s) {
        if(s==null)
            return 0;
	boolean[] flag = new boolean[256];
 
	int result = 0;
	int start = 0;
	char[] arr = s.toCharArray();
 
	for (int i = 0; i < arr.length; i++) {
		char current = arr[i];
		if (flag[current]) {
			result = Math.max(result, i - start);
			// the loop update the new start point
			// and reset flag array
			// for example, abccab, when it comes to 2nd c,
			// it update start from 0 to 3, reset flag for a,b
			for (int k = start; k < i; k++) {
				if (arr[k] == current) {
					start = k + 1; 
					break;
				}
				flag[arr[k]] = false;
			}
		} else {
			flag[current] = true;
		}
	}
 
	result = Math.max(arr.length - start, result);
 
	return result;
}

Java Solution 2 - HashSet

public int lengthOfLongestSubstring(String s) {
    if(s==null || s.length()==0)
        return 0;
 
    HashSet<Character> set = new HashSet<Character>();
 
    int max=0;
 
    int i=0;
    int start=0;
    while(i<s.length()){
        char c = s.charAt(i);
        if(!set.contains(c)){
            set.add(c);
        }else{
            max = Math.max(max, set.size());
 
            while(start<i&&s.charAt(start)!=c){
                set.remove(s.charAt(start));
                start++;
            }
            start++;
        }
 
        i++;
    }
 
    max = Math.max(max, set.size());
 
    return max;
}

or

public int lengthOfLongestSubstring(String s) {
    if(s==null || s.length()==0){
        return 0;
    }
 
    int start=0;
    int max = 0;
 
    HashSet<Character> set = new HashSet<Character>();
    for(int i=0; i<s.length(); i++){
        char c = s.charAt(i);
 
        if(!set.contains(c)){
            set.add(c);
 
            max = Math.max(max, i-start+1);
        }else{
            for(int j=start; j<i; j++){
                set.remove(s.charAt(j));
 
                if(s.charAt(j)==c){
                    start=j+1;
                    break;    
                }
            }        
 
            set.add(c);
        }
    }
 
    return max;
}
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>

  1. tia on 2014-3-5

    Here is my solution with hash:


    public int solution(String s) {

    // IMPORTANT: Please reset any member data you declared, as

    // the same Solution instance will be reused for each test case.

    char[] target = s.toCharArray();

    int pre = 0;

    Hashtable h = new Hashtable();

    for(int i =0; i h.size() ? pre : h.size();

    i = h.get(target[i]);

    h.clear();
    }
    }
    return Math.max(pre, h.size());
    }

  2. junmin on 2014-3-25

    public static int LongestSubStrWithUniqueChars(String s){
    if(s==null || s.isEmpty())
    return 0;

    char[] chars = s.toCharArray();

    int current = 0;//current pos in string
    int length = 0; //current longest substr length
    int pos = 0; //current longest substr starting pos

    for(current =0 ; current<s.length(); current++){
    pos = current;
    boolean[] found = new boolean[256];
    while(current<s.length() && !found[chars[current]]){
    found[chars[current]] = true;
    current++;
    }
    length = Math.max(length, current – pos);
    current = pos;
    }
    return length;
    }

  3. lee on 2014-5-7

    string longestStr = string.Empty;

    int length = str.Length;

    int i = 0;

    Loop:

    string tempLongestStr = string.Empty;

    for (int j = i; j longestStr.Length)

    {

    longestStr = tempLongestStr;

    }

    i = i + tempLongestStr.IndexOf(temp) + 1;

    goto Loop;

    }

    else

    {

    tempLongestStr += temp;

    if (tempLongestStr.Length > longestStr.Length)

    {

    longestStr = tempLongestStr;

    }
    }

    }

    Console.WriteLine(longestStr);
    Console.ReadLine();

  4. ryanlr on 2014-5-7

    It’s the same.

  5. ryanlr on 2014-5-7

    good solution, thanks.

  6. neal on 2014-6-24

    this solution has time limited issue in leetcode.

  7. play_boy on 2014-7-10

    Tia’s solution is good.
    I have the same solution but something different.
    The time : O(n)
    The space may be : O(n)
    and it can output the maxlength substring. (you need to delete the comment tag, and run it)
    like this:

    public static int lengthOfLongestSubstring(String s) {
    char[] arr = s.toCharArray();
    int maxlength = 0;
    int oldstart = 0;
    int newstart = 0;
    // int compare_times = 0; // compare times

    HashMap num = new HashMap(); // recode char and the char index
    HashMap map = new HashMap(); // recode index and the index of char

    for (int i = 0; i < arr.length; i++) {
    // compare_times++; //
    if (num.get(arr[i]) != null) {
    int end = num.get(arr[i]) + 1;
    for (int j = newstart; j < end; j++)
    { // compare times will less than s.length()
    num.remove(map.get(j));
    map.remove(j);
    }
    newstart = end;
    if (maxlength < num.size()) {
    maxlength = num.size();
    oldstart = newstart;
    }
    }
    num.put(arr[i], i);
    map.put(i, arr[i]);
    }
    if (maxlength < num.size()) {
    maxlength = num.size();
    oldstart = newstart;
    }
    // System.out.println("compare_times:" + compare_times); // output the compare times
    // System.out.println(s.substring(oldstart, oldstart + maxlength)); // output the longest substring
    return maxlength;
    }

  8. amit malik on 2014-7-11

    Updated Tia solution to

    1. Find all patterns with no repeating characters.

    2. Find the longest pattern and its size.

    public static void printPatternWithNoReaptingCharsInString(String s) {

    char[] arr = s.toCharArray();

    Map charMap = new HashMap();

    int size = 0;

    List uniquePatterns = new ArrayList();

    StringBuilder str = new StringBuilder();

    for (int i = 0; i < arr.length; i++) {

    if (!charMap.containsKey(arr[i])) {

    charMap.put(arr[i], i);

    } else {

    if (size <= charMap.size()) {

    size = charMap.size();

    if (str.length() <= size) {

    str.delete(0, str.length()).append(

    s.substring(i – size, i));

    uniquePatterns.add(str.toString());

    }

    }

    i = charMap.get(arr[i]);

    charMap.clear();

    }

    }

    System.out.println("Longest Pattern with no repeating characters:"

    + str.toString() + " with size " + size);

    System.out.println("There are in total " + uniquePatterns.size()

    + " patterns with no repeating characters.");

    }

    Below method call:

    printUniquePatterninString("abcdaaabcdaabcdebbpqrstuvaaa");

    will print:

    Longest Pattern with no repeating characters:bpqrstuva with size 9

    There are in total 6 patterns with no repeating characters.

  9. Coder on 2014-7-15

    Solution 2 cannot pass the OJ because of the Time limit.

  10. Cheng Wang on 2014-8-6

    My solution but no idea why it is not correct:

    public class Solution {

    public int lengthOfLongestSubstring(String s) {

    // if the string is empty or has only one character

    if (s.length() < 2) return s.length();

    HashMap hashMap = new HashMap();

    int j = 0;

    int maxLen = 1;

    for (int i = 0; i < s.length(); i++) {

    if (!hashMap.containsKey(s.charAt(i))) {

    hashMap.put(s.charAt(i), i);

    } else {

    maxLen = Math.max(maxLen, i – j);

    j = hashMap.get(s.charAt(i)) + 1;

    hashMap.put(s.charAt(i), i);

    }

    }

    return Math.max(maxLen, s.length() – j);

    }

    }

  11. sudhansu jena on 2014-8-21

    Hi guys My solution simple and works fine.

    public String getLongestSubStringWithoutRepeatedChar(String str){

    ArrayList list=new ArrayList();

    String longestSoFar=””;

    int count=0;

    for(int i=0;i<str.length();i++){

    if(!list.contains(str.charAt(i))){

    list.add(str.charAt(i));

    }else{

    if(count<list.size()){

    count=list.size();

    longestSoFar=getLongestString(list);

    list.clear();

    }

    }

    }

    return longestSoFar;

    }

    private String getLongestString(ArrayList list) {

    StringBuilder sb=new StringBuilder();

    for(Character c:list){

    sb.append(c);

    }

    return sb.toString();

    }

  12. santhoshvai on 2014-9-19

    whats the need for ” i = h.get(target[i]); ” ? It should work without it

  13. santhoshvai on 2014-9-19

    I have written a much simpler version than version 2 (python).. easier to understand. its here, http://ideone.com/BHJlvS

  14. Jonathan Young on 2014-10-12

    This doesn’t work if you pass “abcadeftgh” to your method. It should output 9 instead of 6

  15. santhoshvai on 2014-10-13

    I found the mistake, see this http://ideone.com/WMXFOw

    the LIS for “abcadeftgh” is 7

  16. Jonathan Young on 2014-10-13

    abcadeftgh ==> bcadeftgh (this is the longest substring without repeating element, and its length is 9)

  17. santhoshvai on 2014-10-13

    I am sorry.. i misunderstood LIS.. this http://ideone.com/hcLYgy should fix it

  18. Alex on 2014-11-13

    How about this O(n) solution? It’s easy to understand and allows for the retrieval of the longest substring as well:

    public static int lengthOfLongestSubstring(String word) {

    int start = 0;

    int end = 0;

    int maxStart = 0;

    int maxEnd = 0;

    int[] seen = new int[256];

    for (int i = 0; i < 256; i++) {

    seen[i] = -1;

    }

    for (int i = 0; i = start) {

    start = seen[c] + 1;

    }

    end++;

    seen[c] = i;

    if (end – start > maxEnd – maxStart) {

    maxEnd = end;

    maxStart = start;

    }

    }

    // Return word.substring(maxStart, maxEnd) for actual substring

    return maxEnd – maxStart;

    }

  19. chitti on 2014-11-14

    Does not work for string “eadsabcadcfef”

  20. chitti on 2014-11-14

    corrected one:

    public String getLongestSubStringWithoutRepeatedChar (String str) {
    {
    List list = new ArrayList();
    String longestSoFar =””;
    int count = 0;
    int longestSize=0;

    for (int i = 0; i longestSize) {
    longestSize=count;
    longestSoFar = getLongestString(list);
    System.out.println(longestSoFar);
    }
    count=0;
    list.clear();

    }
    }
    return longestSoFar;
    }
    }

    private String getLongestString (List list) {
    StringBuilder sb = new StringBuilder();
    for (Character c : list) {
    sb.append(c);
    }
    return sb.toString();
    }

  21. chitti on 2014-11-14

    this code handles:

    public String getLongestSubStringWithoutRepeatedChar (String str) {
    {
    List list = new ArrayList();
    String longestSoFar =””;
    int count = 0;
    int longestSize=0;

    //str.length()+1 for capturing longest string at the end.
    for (int i = 0; i < str.length()+1; i++) {
    if (i longestSize) {
    longestSize=count;
    longestSoFar = getLongestString(list);
    System.out.println(longestSoFar);
    }
    count=0;
    list.clear();

    }
    }

    return longestSoFar;
    }
    }

    private String getLongestString (List list) {
    StringBuilder sb = new StringBuilder();
    for (Character c : list) {
    sb.append(c);
    }
    return sb.toString();
    }

  22. Krzysztof Rajda on 2014-11-23

    Proposed solution could be improved. You don’t need to clear the whole map and change i.

    private static String calculateFast(String text) {
    Map map = new HashMap();

    int maxStart = 0;
    int maxEnd = 1;
    int currentStart = 0;

    for (int i = 0; i maxEnd – maxStart) {
    maxStart = currentStart;
    maxEnd = i;
    }
    currentStart = firstOccurrenceIndex + 1;
    }
    map.put(c, i);
    }

    if (text.length() – currentStart > maxEnd – maxStart) {
    maxStart = currentStart;
    maxEnd = text.length();
    }

    return text.substring(maxStart, maxEnd);
    }

  23. Jianwei Chen on 2014-11-27

    this is simpler.
    public static lls(String s) {
    HashMap map = new HashMap();

    int maxStart = 0;

    int pre = 0;

    for(int i = 0; i pre) {

    pre = map.size();

    maxStart = map.get(c);

    }

    }

    map.put(c, i);

    }

    return s.substring(maxStart, maxStart+pre);
    }

  24. Wally Osmond on 2014-12-6

    Hey guys,

    Isn’t the best solution just a simple for loop with an if and some counters? Perhaps my solution is too simple and crashes or returns the results incorrectly somehow??? I tested it for the longest string and the beginning/end/middle and I believe it works.

    public static int getNoRepeatLen (String str) {

    int max=0,tLen=0;

    for(int i=1;i<str.length();i++) {

    if(str.charAt(i-1) == str.charAt(i)){

    max=Math.max(tLen+1,max);

    tLen=0;

    } else {

    tLen++;

    }

    }

    return Math.max(max,tLen);

    }

  25. Wally Osmond on 2014-12-6

    public static int getNoRepeatLen (String str) {

    int max=0,tLen=0;

    for(int i=1;i<str.length();i++) {

    if(str.charAt(i-1) == str.charAt(i)){

    max=Math.max(tLen+1,max);

    tLen=0;

    } else {

    tLen++;

    }

    }

    return Math.max(max,tLen);

    }

  26. Zy on 2014-12-14

    Hi Ryan,

    I like your site a lot, but I noticed that the recently-added social area on every post is blocking the sight.

    Hopefully this can be fixed and I can enjoy reading your site again.

  27. Zaga on 2014-12-25

    So I came up with an O(n) solution in python, please help me detect in what cases it can possibly fail

    #put test string here

    string = “eadsabcadcfef”

    indexOfSubsequence = 0

    tempIndexOfSubsequence = 0

    lenghtOfSubsequence = 0

    tempLenghtOfSubsequence = 0

    tableOfCharsIndex = [-1] * 26

    for i in xrange(0, len(string)):

    indexOfChar = ord(string[i]) – 97

    if tableOfCharsIndex[ indexOfChar ] == -1 or tableOfCharsIndex[ indexOfChar ] lenghtOfSubsequence :

    lenghtOfSubsequence = tempLenghtOfSubsequence

    indexOfSubsequence = tempIndexOfSubsequence

    else:

    if tempLenghtOfSubsequence > lenghtOfSubsequence :

    lenghtOfSubsequence = tempLenghtOfSubsequence

    indexOfSubsequence = tempIndexOfSubsequence

    tempIndexOfSubsequence = i

    tempLenghtOfSubsequence = 1

    tableOfCharsIndex[ indexOfChar ] = i

    print string[ indexOfSubsequence : indexOfSubsequence + lenghtOfSubsequence ]

    print lenghtOfSubsequence

  28. neckBeardThePirate on 2015-1-2

    how is solution two O(n^3)?

  29. Tarun Singh on 2015-1-12

    I think Following is O(n) Solution 😀

    public static int lengthOfLongestSubstring(String s) {

    char[] arr = s.toCharArray();

    int pre = 0;

    int k=0;

    boolean flag = true;

    HashMap map = new HashMap();

    for (int i = 0; i pre)

    pre=l;

    k = map.get(arr[i]);

    map.put(arr[i],i);

    k++;

    }

    }

    if(flag) pre = arr.length;

    return pre;

    }

  30. Arpit Pandey on 2015-2-19

    “bbabceabcdbb” fails with this string returns a wrong string

  31. ryanlr on 2015-2-26

    Your code only compares the two consecutive characters, it can not handle case like “a”.

  32. ryanlr on 2015-2-26

    Thanks. I think the problem is fixed now.

  33. ryanlr on 2015-2-26

    Your code is not right, for example, “aab”.

  34. ryanlr on 2015-2-26

    You solution is wrong. maxStart is not updated correctly.

  35. Tiago on 2015-2-27

    I think the following works too:

    static public String nonRepeated(String input){

    char[] charAInput = input.toCharArray();
    String aux = “”;
    String resultSubStr = “”;

    if(input.length() == 1)
    return input;

    for(int i =0; i < charAInput.length; i++ ){

    if(!aux.contains("" + charAInput[i])){

    aux = aux.concat("" + charAInput[i]);

    }
    else
    aux = "" + charAInput[i];

    if(resultSubStr.length() < aux.length())
    resultSubStr = aux;
    }

    System.out.println(resultSubStr);

    return resultSubStr;

    }

  36. ryanlr on 2015-2-27

    No, it doesn’t. For example, given “abac”, when it meets the second “a”, aux should not be set to “a”, instead it should be set to “ba”.

  37. Mehmet on 2015-3-8

    What is the time and space complexity of first solution?

  38. Parag Chaudhari on 2015-4-3
  39. Taoufik Bdiri on 2015-4-11

    For the solution using the HashMap, I think the following line :
    i = map.get(arr[i]);
    should be changed to :
    i = map.get(arr[i])+1;
    Otherwise you will get an infinite loop ?

  40. Adil qureshi on 2015-6-20

    can you explain why second one in On3 .. i cant get it … thanks

  41. Sahil Singla on 2015-6-23

    I believe this is O(n):

    public static int lengthOfLongestSubstring(String s) {
    if(s==null)
    return 0;
    char[] arr = s.toCharArray();
    int pre = 0;
    HashMap map = new HashMap();
    int j = 0;
    int curr = 0;
    for (int i = 0; i < arr.length; i++) {
    if (!map.containsKey(arr[i]) || map.get(arr[i]) < j) {
    map.put(arr[i], i);
    curr++;
    } else {
    pre = Math.max(pre, curr);
    j = map.get(arr[i]) + 1;
    curr = i + 1 – j;
    map.put(arr[i], i);
    }
    }
    return Math.max(pre, curr);
    }

  42. Edmond Hong on 2015-7-11

    I don’t think you need add the statement: ‘map.get(arr[i]) < j'

  43. Vimukthi Weerasiri on 2015-7-15

    A simpler O(n) solution.

    public int lengthOfLongestSubstring(String s) {
    HashMap map = new HashMap();
    if (s == null || s.length() == 0) return 0;
    int first = 0, second = -1, answer = 0;
    while (first != s.length()) {
    Integer previousOccurrence = map.put(s.charAt(first), first);
    if (previousOccurrence != null) second = Math.max(second, previousOccurrence);
    answer = Math.max(answer, first – second);
    first++;
    }
    return answer;
    }

  44. test on 2015-7-17

    second = -1 is pretty weird.

  45. Vimukthi Weerasiri on 2015-7-17

    Thanks. Agree. Updated the code with some refactoring 🙂 Intention was to initialize it one prior to the rightPointer. Comments are welcome!

  46. Satish on 2015-8-5

    public static String uniqueCharSubstring(String str) {
    String result = “”;
    int len = str.length();
    HashMap map = new HashMap();
    char[] c = str.toCharArray();
    int right = 0, max = 0;
    for (int left = 0; left < len; left++) {
    while (right max) {
    max = right – left;
    result = str.substring(left, right + 1);
    }
    right++;
    }
    }
    return result;
    }

  47. dtReloaded on 2015-8-8

    List list = new ArrayList();

    for(int i=0 ; i<a.length();i++){

    if(!list.contains(a.charAt(i))){

    list.add(a.charAt(i));

    }

    else

    break;

    }

    System.out.println("The String Lengtht" +a.length());

  48. Sahil Singla on 2015-8-25

    It is required. Consider the case “dabcabcde”. If ‘map.get(arr[i]) < j' is not done then, for the iteration with "i=7" it would be computed that "d" has already contained in the HashMap and also the logic inside the "else" will fail and compute to give 'curr=7'.

  49. NB**** on 2015-9-12


    void LargestNonRepeatedSubStr() {
    string str = "abcabcbb";
    int max_length = 0;
    int i = 0;
    while (i < str.length()) {
    set check_set;
    int j = i;
    int length = 0;
    while (j < str.length()) {
    if (check_set.find(str[j]) != check_set.end()) {
    break;
    } else {
    check_set.insert(str[j]);
    length++;
    }
    j++;
    }
    check_set.clear();
    max_length = std::max(max_length, length);
    i++;
    }
    cout << "The max length is: " << max_length << "n";
    }

  50. Holden on 2015-9-17

    Why time complexity of second approach is O(n^3)?

  51. southie on 2015-11-12

    O(n) solution with LinkedHashSet JAVA !

    public class LongestPalindromeWithoutRepChar {

    public static int lengthOfLongestSubstring(String s) {
    int maxCount=0;
    if(s.length() < 2) return s.length();
    Set hs = new LinkedHashSet();

    for(int i=0;i maxCount) maxCount = hs.size();
    Iterator itr = hs.iterator();
    Character curr = null;
    while(c!=curr)
    {
    curr = itr.next();
    itr.remove();
    }
    }
    }

    return maxCount;
    }
    }

  52. pm on 2015-11-27

    public class LCSWIthoutRepeating{
    public static void main(String args[]){
    String str = “aaaaapritikamehta”;
    LinkedHashMap hash = new LinkedHashMap();
    int maxLen =0;
    int max =0;
    int num =0;
    int arr[] = new int[26];
    for(int i =0;i<str.length();i++){
    char c = str.charAt(i);
    if(hash.get(c) == null){
    hash.put(c, i);
    max++;
    }else{
    maxLen = i – hash.get(c)max?maxLen:max);
    }

    }

  53. CRH on 2015-12-21

    Why is the time complexity mentioned as n^3 for Java Solution 2 above? It should be O(n). The first loop is O(n) and in that main loop i is getting pushed back to an already visited location. So effectively we may end up looping through the whole loop 2n times. That still means O(n), then why n^3 is mentioned.

    Please help!

  54. Ankit Shah on 2015-12-24

    Following works and it also prints the substring

  55. Truong Khanh Nguyen on 2016-1-25
  56. Adrian on 2016-1-29

    Following code is O(N) time complexity and constant space complexity O(1).

    public int LongestSubstringWithoutRepeatingCharacters(String src)
    {
    if (src == null || src.Length == 0)
    return 0;

    // v[j] stores i position of the src[i] character, where j = src[i]
    int[] v = new int[256];
    // Initialize visited state
    for (int i = 0; i < 256; ++i)
    v[i] = -1;

    v[src[0]] = 0;

    // start position of the longest string of non repeating characters
    int start = 0;
    // max length of string with non repeating characters so far
    int max_len = 1;

    for (int i = 1; i < src.Length; ++i)
    {
    if (v[src[i]] == -1)
    {
    v[src[i]] = i;
    ++max_len;
    }
    else
    {
    int cur_len = i - start;
    if (max_len < cur_len)
    max_len = cur_len;

    // move start of the substring with non repeating characters
    // after already visited(repeated) character
    start = v[src[i]] + 1;
    }
    }

    return max_len;
    }

  57. Eugene Arnatovich on 2016-3-5

    Simplest solution:

    //Longest Substring Without Repeating Characters (Java)
    public int solution(String s) {
    Set set = new LinkedHashSet();
    for (char c : s.toCharArray()) {
    set.add(c);
    }
    return set.size();
    }

  58. Larry Okeke on 2016-3-15

    Lol! Are you kidding?

  59. Larry Okeke on 2016-3-15

    simple solution

    import java.util.*;

    public class longest_substring{

    /*

    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.

    */

    public static void main(String[] args){

    System.out.println("longest " +get_longest(args[0]));

    }

    public static int get_longest(String str){

    HashSet wordSet = new HashSet();

    int longest = 0;

    for(int i = 0; i < str.length(); i++){

    for(int j = i; j longest){

    longest = wordSet.size();

    }

    wordSet.clear();

    break;

    }

    }

    }

    return longest;

    }

    }

  60. Eugene Arnatovich on 2016-3-15

    Yep. That was my misunderstanding… Hope now it is better…

  61. jeevs on 2016-7-28

    public class longestsubstring {

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner in=new Scanner(System.in);
    ArrayList a=new ArrayList();
    String s=in.next();
    String temp=””;
    String target=””;
    for(int i=0;itarget.length())
    target=temp;
    a.clear();
    temp=””;
    }
    }
    System.out.print(target);
    }

  62. Milan on 2016-8-27

    //time : O(n) space : O(n)

    public class Solution {
    public int lengthOfLongestSubstring(String s) {
    int start = 0,max = 0,i =0;
    Map lookup = new HashMap();
    for (;i= start) {
    max=Math.max(max,i-start);
    start=lookup.get(ch)+1;
    }
    lookup.put(ch,i);
    }
    max=Math.max(max,i-start);
    return max;
    }
    }

  63. Badrinath on 2016-9-5

    simple Solution is to add every character to Hash set and get the size of it. As Set doesn’t store duplicates this is the easiest and simple way to get the count.

    below is the code

    static int longest(String s){
    int result = 0;
    int a = s.length();
    Set set = new HashSet();
    for(int i=0; i<a-1 ; i++){
    set.add(s.charAt(i));
    }
    System.out.println("Length of the string is" + set.size());
    return result;
    }

  64. Mel on 2016-9-15


    static int lengthOfLongestSubstring(String s){
    if(s==null || s.length()==0)
    return 0;

    boolean []flag=new boolean[256];
    int count=0;
    int max=Integer.MIN_VALUE;
    for(int i=0;imax){
    max=count;
    }
    flag[c]=false;
    count=0;
    }

    }
    return max;
    }

  65. vuqar dadalov on 2016-9-27

    This is My Solution

    public class Solution {
    public int lengthOfLongestSubstring(String s) {

    if(s.trim().length() == 0) {
    return 0;
    }

    char [] strArr = s.toCharArray();

    HashMap map = new HashMap();
    int maxLen = 0;
    int firstIndex = 0;
    int lastIndex = 0;

    for(int i=0; i maxLen){
    maxLen = i – firstIndex;
    }

    if(map.get(strArr[i]) >= firstIndex){
    firstIndex = map.get(strArr[i]) + 1;
    }

    map.remove(map.get(strArr[i]));
    }
    map.put(strArr[i],i);
    lastIndex = i;
    }

    if((lastIndex – firstIndex + 1) > maxLen){
    maxLen = lastIndex – firstIndex + 1;
    }

    return maxLen;
    }
    }

  66. Ping Zhang on 2017-1-1

    Here is my javascript solution with great details:

    var lengthOfLongestSubstring = function(s) {
    const valueIdxHash = {};
    var longest = 0;
    var startIdx = 0;
    for(var i = 0; i < s.length; i++) {
    if(s[i] in valueIdxHash) {
    startIdx = Math.max(startIdx, valueIdxHash[s[i]] + 1);
    }
    valueIdxHash[s[i]] = i;
    longest = Math.max(longest, i – startIdx + 1);
    }
    return longest;
    };

    Checkout my blog for detailed explanation: https://algorithm.pingzhang.io/String/longest_substring_without_repeating_characters.html

  67. Gaurav Gupta on 2017-4-8

    Below is a solution that is in O(n) time complexity and O(1) space.
    This solution uses hash table of size 26 (number of alphabets).
    I have tested it for as many cases as I could think of. Have a look:

    #include
    #include
    main(){
    char st[] = “geeksforgeeks”;
    int hash[26] = {0};

    int i, j = -1, max = 0, res = 1;

    for (i = 0; i < strlen(st); i++) {
    if ( (j != -1 && hash[st[i] – 'a'] < j) || (j == -1 && hash[st[i] – 'a'] == 0)) {
    if (res < i – j) res = i – j;
    } else {
    j = hash[st[i] – 'a'];
    }
    hash[st[i] – 'a'] = i;
    }
    printf("%dn", res);
    }

Leave a comment

*