Sunday, May 29, 2016

longest continuous substring with unique characters

On repeating char, adjust start (last index +1) and update it's last index (i).
s: abcade
   |--|
    |----|5

s: abbded
   |-|
     |--|3
       |-|

s: aa
   ||1
    ||

s: abc
   |--|3
string (s):
    if s == null:
        throw
    if s == "":
        return ""
    maxend = -1, maxstart = 0
    start = 0
    cindexMap = new
    for i = 0, i < s.length(), i++:
        c = s[i]
        if cindexMap.hasKey(c):
            start = cindexMap[c] +1
        if i-start > maxend-maxstart:
            maxend = i, maxstart = start
        cindexMap[c] = i
    return s.substring(maxstart, maxend -maxstart +1)
[Hat tip to SM]

1 comment:



  1. private static String extractMap(Map map){

    StringBuffer sB = new StringBuffer();
    Iterator it = map.entrySet().iterator();

    while(it.hasNext()){
    //Map.Entry.
    Map.Entry entry = (Map.Entry) it.next();
    sB.append(entry.getKey());
    }

    return sB.toString();
    }

    private static String processMap(String input){

    Map repeatMap = new LinkedHashMap<>();
    int i = 0;

    String longString = "";
    do{

    if(!repeatMap.containsKey(input.charAt(i))){
    repeatMap.put(input.charAt(i),i);
    }
    else{

    int val = repeatMap.get(input.charAt(i));
    i = val;
    String retString = extractMap(repeatMap);
    repeatMap.clear();
    if(longString.length() < retString.length()){
    longString = retString;
    }
    }
    i++;

    }while(i < input.length());

    return longString;
    }

    ReplyDelete