使用HashMap或Hashset优化使用循环判断字符串中是否含有重复元素

原本遇到判断字符串中是否含有重复元素的问题总是使用for循环遍历进行判断,这一方法则需要O(n3)的时间复杂度,如果本身方法处于几个循环中,就会指数倍增加时间复杂度。类似于如下代码:

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;
    }
}
使用三层for循环

一种更快的判断方法则是使用HashMap或Hashset,利用HashMap中的containsValue()或Hashset中的contains()方法,可以直接判断出字符串中是否有重复的元素,需要的时间复杂度为O(n2),我使用的是HashMap,代码如下:

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

可以看见,代码中只使用了两层for循环,可以明显加快代码执行时间,要记住每次循环后要使用clear()方法将HashMap中所有映射删除。

原文地址:https://www.cnblogs.com/anthonyhoo/p/12304426.html