只能說仍是太菜,抄的網上大神的作法:
idea:java
代碼以下:ide
public int longestSubstring(String s, int k) { if (k == 1) return s.length(); int res = 0, i = 0, n = s.length(); while (i + k <= n){ int[] m = new int[26]; int mask = 0, max_idx = i; for (int j = i; j < n; j ++){ int t = s.charAt(j) - 'a'; m[t]++; if (m[t] < k) mask |= (1 << t); else mask &= (~(1 << t)); if (mask == 0){ res = Math.max(res, j - i + 1); max_idx = j; } } i = max_idx + 1; } return res; }
下面一種作法的思路是:把串的小於k的字符當作間隔,直到這個串的每個字符都大於等於k爲止。
(一開始有這個思路,沒寫出來- - )idea
public int helper(String s, int k, int left, int right){ int len = right - left + 1; if (len <= 0) return 0; int i, j, maxlen = 0; int[] m = new int[26]; for (i = left; i <= right; i++) m[s.charAt(i) - 'a']++; for(i = left, j = left; i <= right; i++){ if (m[s.charAt(i) - 'a'] < k){ maxlen = Math.max(maxlen, helper(s, k, j, i - 1)); j = i + 1; } } if (j == left) return len; else return Math.max(maxlen, helper(s, k, j, i - 1)); } public int longestSubstring(String s, int k) { return helper(s, k, 0, s.length() - 1); }
還有滑動窗口的作法,接下來更新。code