求字符串最大不重复串
思路:
利用左右指针和map数据结构
求左右指针的最大间隔
遍历字符数组,如果在map中不存在,则右指针右移,并求最大长度
如果在map中存在,则左指针右移
import java.util.*; public class Client { public static void main(String[] args) { String str = "abcdbe"; int i = maxSubLen(str); System.out.println(i); } /** * 求不重复字符的长度 */ static int maxSubLen(String str) { int maxLen = 0; int left = 0; int right = 0; char[] chars = str.toCharArray(); int n = str.length(); Object mapVal = new Object(); Map<Character, Object> map = new HashMap<>(); while (right < n) { Object val = map.get(chars[right]); if (val == null) {// 没有重复字符 map.put(chars[right], mapVal); right++; maxLen = Math.max(right - left, maxLen); } else {// 有重复字符 while (chars[left] != chars[right]) { left++; } left++; right++; } } return maxLen; } }