leetcode 467. Unique Substrings in Wraparound String | 467. 环绕字符串中唯一的子字符串(动态规划)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 467. Unique Substrings in Wraparound String | 467. 环绕字符串中唯一的子字符串(动态规划)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
https://leetcode.com/problems/unique-substrings-in-wraparound-string/
題解
1、dp 超時版本
class Solution {public int findSubstringInWraproundString(String p) {HashSet<Integer>[] arr = new HashSet[26]; // <結尾字母,長度>for (int i = 0; i < 26; i++) {arr[i] = new HashSet();}arr[p.charAt(0) - 'a'].add(1);int curLen = 1; // 避免誤將斷鏈情況計入結果for (int i = 1; i < p.length(); i++) {arr[p.charAt(i) - 'a'].add(1);if (p.charAt(i) == 'a' && p.charAt(i - 1) == 'z') {curLen++;for (int len : arr[25]) {if (len + 1 <= curLen) arr[0].add(len + 1);}} else if (p.charAt(i - 1) == p.charAt(i) - 1) {curLen++;for (int len : arr[p.charAt(i - 1) - 'a']) {if (len + 1 <= curLen) arr[p.charAt(i) - 'a'].add(len + 1);}} else {curLen = 1;}}int result = 0;for (int i = 0; i < 26; i++) {result += arr[i].size();}return result;} }2、dp 答案版本
參考:Concise Java solution using DP
After failed with pure math solution and time out with DFS solution, I finally realized that this is a DP problem…
The idea is, if we know the max number of unique substrings in p ends with 'a', 'b', ..., 'z', then the summary of them is the answer. Why is that?
Hope I made myself clear…
class Solution {public int findSubstringInWraproundString(String p) {int[] dp = new int[26]; // <結尾字母,以當前字母結尾的最長串長度>dp[p.charAt(0) - 'a'] = 1;int curLen = 1;for (int i = 1; i < p.length(); i++) {if (p.charAt(i - 1) == p.charAt(i) - 1 || p.charAt(i) == 'a' && p.charAt(i - 1) == 'z') {curLen++;} else {curLen = 1;}dp[p.charAt(i) - 'a'] = Math.max(dp[p.charAt(i) - 'a'], curLen);}int result = 0;for (int i = 0; i < 26; i++) {result += dp[i];}return result;} }總結
以上是生活随笔為你收集整理的leetcode 467. Unique Substrings in Wraparound String | 467. 环绕字符串中唯一的子字符串(动态规划)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 1293. Short
- 下一篇: leetcode 782. Transf