Use HashMap or Hashset Optimizer containing a repeating cycle is determined using the string element

Problems encountered original string is determined whether it contains repeat elements always used for loop iterates judgment, this solution requires O (n- . 3 complexity) time, if the method is in itself a few cycles, it will increase exponentially time complexity. Similar to the following code:

String[] a = s.split("");
int max = 1;
for(int i = 0; i < a.length; i++){
    String[] b = new String[a.length - i];
    b[0] = a[i];
    int permax = 1;            
    for(int j = i + 1, k = 1; k < b.length && j < a.length; j++, k++){
        boolean repeat = false;
        for(String c: b){
            if(a[j].equals(c)){
                repeat = true;
            }
        }
        if(repeat == false){
            b[k] = a[j];
            permax++;
            if(permax > max){
            max = permax;
            }
        }
        else 
            break ;
    }
}
Use three for loop

For a faster method of determining it is to use HashMap or Hashset, containsValue use in the HashMap () or contains Hashset in () method can be directly determined whether the character string repeated elements, the time required complexity is O (n- 2 ), I use a HashMap, code is as follows:

String[] a = s.split("");
HashMap<Integer, String> map = new HashMap<>();
int max = 1;
for(int i = 0; i < a.length; i++){
    map.clear();
    map.put(i, a[i]);
    int permax = 1;            
    for(int j = i + 1 ;j < a.length; j++){
        if(!map.containsValue(a[j])){
            map.put(j, a[j]);
            permax++;
            if(permax > max){
            max = permax;
            }
        }
        else 
            break ;
    }
}

You can see, the code is only used for two-cycle, can significantly accelerate code execution time, keep in mind that after each cycle to use clear () method to delete all of the mappings HashMap.

Guess you like

Origin www.cnblogs.com/anthonyhoo/p/12304426.html