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.

Analysis

The basic idea to solve this problem is using an extra data structure to track the unique characters in a sliding window. Both an array and a hash set work for this purpose.

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

Using a HashSet can simplify the code a lot.

/*
  pwwkew
i | 
j |
 
i |
j   |
 
i   |
j   |
 
*/
public int lengthOfLongestSubstring(String s) {
    if(s==null||s.length()==0){
        return 0;
    }
 
    HashSet<Character> set = new HashSet<>();
    int result = 1;
    int i=0; 
    for(int j=0; j<s.length(); j++){
        char c = s.charAt(j);
        if(!set.contains(c)){
            set.add(c);
            result = Math.max(result, set.size());
        }else{
            while(i<j){
                if(s.charAt(i)==c){
                    i++;
                    break;
                }
 
                set.remove(s.charAt(i));
                i++;
            }
        }    
    }
 
    return result;
}

83 thoughts on “LeetCode – Longest Substring Without Repeating Characters (Java)”


  1. def substr(input):
    r = []
    prev = ''
    for chr in input:
    if chr in r:
    if len(r)>len(prev):
    prev = r
    id = r.index(chr)
    r = r[id+1:]
    r.append(chr)
    if len(r)> len(prev):
    return r, len(r)
    else:
    return prev, len(prev)


  2. A bit simpler solution with less variables and relatively meaningful names.


    int longestSubstrWithoutRepeatingChars(String s)
    {
    if (s == null || s.isEmpty()) return 0;

    int max = 0;

    HashSet subStrChars = new HashSet();

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

    if (subStrChars.add(c))
    {
    max = Math.max(max, subStrChars.size());
    }
    else
    {
    /* Remove chars up to duplicate */
    for (int j = i - subStrChar.size() ; j < i ; j++)
    {
    char toRemove = s.charAt(j);

    if (c == toRemove) break; /* No need to remove the current. */

    subChar.remove(toRemove);
    }
    }
    }

    return max;
    }

  3. public int LongestSubstring(string s)
    {
    if (string.IsNullOrWhiteSpace(s))
    {
    return 0;
    }

    List stringCounts = new List();

    for(var i = 0; i sc.Length).Take(1).First();

    return longest.Length;
    }


  4. public static String subStringMasLargo(String vector)
    {
    String subStringMasLargo = "";
    String cadena = String.valueOf(vector.charAt(0));

    for(int i=1; i subStringMasLargo.length())
    {
    subStringMasLargo = cadena;
    cadena = String.valueOf(vector.charAt(i));
    }
    else
    {
    cadena = String.valueOf(vector.charAt(i));
    }
    }
    }

    return subStringMasLargo;
    }

    public static boolean laContiene(String cadena, String letra)
    {
    for (int i=0; i<cadena.length(); i++)
    {
    if(String.valueOf(cadena.charAt(i)).equals(letra))
    {
    return true;
    }
    }

    return false;
    }


  5. public static String subStringMasLargo(String vector)
    {
    String subStringMasLargo = "";
    String cadena = String.valueOf(vector.charAt(0));

    for(int i=1; i subStringMasLargo.length())
    {
    subStringMasLargo = cadena;
    cadena = String.valueOf(vector.charAt(i));
    }
    else
    {
    cadena = String.valueOf(vector.charAt(i));
    }
    }
    }

    return subStringMasLargo;
    }

    public static boolean laContiene(String cadena, String letra)
    {
    for (int i=0; i<cadena.length(); i++)
    {
    if(String.valueOf(cadena.charAt(i)).equals(letra))
    {
    return true;
    }
    }

    return false;
    }


  6. public static String subStringMasLargo(String vector)
    {
    String subStringMasLargo = "";
    String cadena = String.valueOf(vector.charAt(0));

    for(int i=1; i subStringMasLargo.length())
    {
    subStringMasLargo = cadena;
    cadena = String.valueOf(vector.charAt(i));
    }
    else
    {
    cadena = String.valueOf(vector.charAt(i));
    }
    }
    }

    return subStringMasLargo;
    }

    public static boolean laContiene(String cadena, String letra)
    {
    for (int i=0; i<cadena.length(); i++)
    {
    if(String.valueOf(cadena.charAt(i)).equals(letra))
    {
    return true;
    }
    }

    return false;
    }

  7. Nice catch, Ash. I haven’t had time to look at your fix but I can visually see how that test case will fail. I’ll see if there is a fix with better efficiency when I get some time 🙂

  8. Hi Bukary,

    This code will not work for “dvdf”

    output should be 3 -> “vdf”
    instead the output will be 2 ->”dv” or “df”


  9. Java One-Loop Solution. See my short program that solves this problem in one loop and more efficient than the above solution. Time O(n)

    public static int lengthOfLongestSubstring(String str){
    Set set = new HashSet();
    int longest=0, check=0;

    for(int i=0; i < str.length(); i++){
    if(!set.contains(str.charAt(i))){
    set.add(str.charAt(i));
    check++;
    }else {
    longest = Math.max(check,longest);
    set.clear();
    check = 1;
    }
    }
    longest = Math.max(check,longest);
    return longest;
    }

  10. In the Java Solution 2: What purpose does the start variable serve? I could not understand this part: while(start<i&&s.charAt(start)!=c){
    set.remove(s.charAt(start));
    start++;
    }
    start++;
    Please help me

  11. for(j=i+1;jmax)—— showing error in this line in eclipse. could you tell me what is the error is about?

  12. import java.util.*;
    public class Subst {
    public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    System.out.println(“Enter String”);
    String word=sc.next(),maxWord=””,newWord=””;
    int l=word.length(),i,j,max=0;
    for(i=0;i<l;i++){
    newWord=word.substring(i);
    for(j=i+1;jmax){
    max=j-i;
    maxWord=word.substring(i,j);
    }
    }
    System.out.println(maxWord);
    }
    }

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

  14. 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

  15. 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;
    }
    }


  16. 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;
    }

  17. 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;
    }

  18. //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;
    }
    }

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

  20. 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;

    }

    }

  21. 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();
    }

  22. 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;
    }

  23. 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!

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

    }

  25. 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;
    }
    }


  26. 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";
    }

  27. 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'.

  28. 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());

  29. 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;
    }

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

  31. 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;
    }

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

  33. 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 ?

  34. 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”.

  35. 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. 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;

    }

  37. 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

  38. 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.

  39. 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);

    }

  40. 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);

    }

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

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

  43. 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();
    }

  44. 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();
    }

  45. 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;

    }

  46. 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();

    }

  47. 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);

    }

    }

  48. 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.

  49. 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;
    }

  50. 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();

  51. 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;
    }

  52. 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());
    }

Leave a Comment