找到字符串中无重复最长的字符子串

/**
 * Created by lxw, [email protected] on 2017/11/1.
 * 找到字符串中无重复最长的字符子串
 */
public class maxUniqueString {

    public int maxUnique(String str){
        if(str == null || str.equals("")){
            return 0;
        }
        char[] chars = str.toCharArray();
        int[] map  =new int[256];
        for (int i=0; i< 256; i++){
            map[i] = -1;
        }
        int len  =0;
        int pre = -1;
        int cur  =0;
        for (int i=0; i< chars.length; i++){
            pre = Math.max(pre, map[chars[i]]);
            cur = i - pre;
            len = Math.max(cur, len);
            map[chars[i]] = i;
        }
        return len;
    }

    public static void main(String[] args){
        maxUniqueString tmp = new maxUniqueString();
        String str1 = "abcd";
        String str2 = "aabcb";
        System.out.println(tmp.maxUnique(str1));
        System.out.println(tmp.maxUnique(str2));
    }
}

你可能感兴趣的:(找到字符串中无重复最长的字符子串)