File tree 2 files changed +39
-0
lines changed
2 files changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ package medium ;
2
+
3
+ public class UniqueSubstringsinWraparoundString {
4
+ /**A naive solution would definitely result in TLE.
5
+ * Since the pattern keeps repeating, DP is the way to go.
6
+ * Because the input consists merely of lowercase English letters, we could maintain an array of size 26,
7
+ * keep updating this array, counting the substrings that end with this letter, keep updating it with the largest one possible.
8
+ *
9
+ * Inspired by this: https://discuss.leetcode.com/topic/70658/concise-java-solution-using-dp*/
10
+ public static int findSubstringInWraproundString (String p ) {
11
+ if (p == null || p .isEmpty ()) return 0 ;
12
+ if (p .length () < 2 ) return p .length ();
13
+ int count = 0 ;
14
+ int [] dp = new int [26 ];
15
+ dp [p .charAt (0 ) - 'a' ] = 1 ;
16
+ int len = 1 ;
17
+ for (int i = 1 ; i < p .length (); i ++) {
18
+ if (p .charAt (i ) - 1 == p .charAt (i -1 ) || (p .charAt (i ) == 'a' && p .charAt (i -1 ) == 'z' )){
19
+ len ++;
20
+ } else {
21
+ len = 1 ;
22
+ }
23
+ dp [p .charAt (i ) - 'a' ] = Math .max (len , dp [p .charAt (i ) - 'a' ]);
24
+ }
25
+
26
+ for (int i : dp ){
27
+ count += i ;
28
+ }
29
+ return count ;
30
+ }
31
+
32
+ public static void main (String ...args ){
33
+ // String p = "a";
34
+ // String p = "abcgha";
35
+ String p = "zab" ;
36
+ System .out .println (findSubstringInWraproundString (p ));
37
+ }
38
+ }
Original file line number Diff line number Diff line change 1
1
# fishercoderLeetcode
2
2
| # | Title | Solutions | Time | Space | Difficulty | Tag | Notes
3
3
|-----|----------------|---------------|---------------|---------------|-------------|--------------|-----
4
+ |467|[ Unique Substrings in Wraparound String] ( https://leetcode.com/problems/unique-substrings-in-wraparound-string/ ) |[ Solution] ( ../../blob/master/MEDIUM/src/medium/UniqueSubstringsinWraparoundString.java ) | O(n) |O(1) | Medium| DP
4
5
| 463| [ Island Perimeter] ( https://leetcode.com/problems/island-perimeter/ ) | [ Solution] ( ../../blob/master/EASY/src/easy/IslandPerimeter.java ) | O(m* n)| O(1) | Easy|
5
6
| 462| [ Minimum Moves to Equal Array Elements II] ( https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/ ) | [ Solution] ( ../../blob/master/MEDIUM/src/medium/MinimumMovestoEqualArrayElementsII.java ) | O(nlogn) | O(1) | Medium|
6
7
|459|[ Repeated Substring Pattern] ( https://leetcode.com/problems/repeated-substring-pattern/ ) |[ Solution] ( ../../blob/master/EASY/src/easy/RepeatedSubstringPattern.java ) | O(n)|O(n) | Easy| KMP
You can’t perform that action at this time.
0 commit comments