获取最长的不重复子串(使用HashMap)

package com.oracle.test;

import java.util.HashMap;
import java.util.Map;

import org.testng.annotations.Test;

public class LongestSubStrTest {
    
    public String getLongestSubstr(String s) {
        
        if(s.length() == 0) return "";
        
        
        Map m = new HashMap();
        int left = -1;
        
        int maxLen = 0;
        
        String res = "";
        for(int i=0;i left) {
                left = m.get(s.charAt(i));
            }
            
            m.put(s.charAt(i), i);
            maxLen = Math.max(maxLen, i-left);
            String tmp = s.substring(left+1,i+1);
            
            if(tmp.length() > res.length()) {
                res = tmp;
            }
        }
        
        return res;
    }
    @Test
    void testLongestSubstr() {
        System.out.println(getLongestSubstr("abcdabcdefgaabbcc"));
    }

}

你可能感兴趣的:(获取最长的不重复子串(使用HashMap))