标签:explore exp time tput ice sts poi new available
Given two integers A
and B
, return any string S
such that:
S
has length A + B
and contains exactly A
‘a‘
letters, and exactly B
‘b‘
letters;‘aaa‘
does not occur in S
;‘bbb‘
does not occur in S
.
Example 1:
Input: A = 1, B = 2
Output: "abb"
Explanation: "abb", "bab" and "bba" are all correct answers.
Example 2:
Input: A = 4, B = 1
Output: "aabaa"
Note:
0 <= A <= 100
0 <= B <= 100
S
exists for the given A
and B
.1 class Solution { 2 private String ans = null; 3 public String strWithout3a3b(int A, int B) { 4 int[] counts = new int[2]; 5 counts[0] = A; 6 counts[1] = B; 7 dfs(counts, new StringBuilder()); 8 return ans; 9 } 10 private boolean dfs(int[] counts, StringBuilder sb) { 11 if(sb.length() >= 3) { 12 String sub = sb.substring(sb.length() - 3); 13 if(sub.equals("aaa") || sub.equals("bbb")) { 14 return false; 15 } 16 } 17 if(counts[0] == 0 && counts[1] == 0) { 18 return true; 19 } 20 //if there are a available, try pick a first 21 if(counts[0] > 0) { 22 sb.append(‘a‘); 23 counts[0]--; 24 if(dfs(counts, sb)) { 25 ans = sb.toString(); 26 return true; 27 } 28 sb.deleteCharAt(sb.length() - 1); 29 counts[0]++; 30 } 31 //if using a does not work, or there are no a, pick b 32 if(counts[1] > 0) { 33 sb.append(‘b‘); 34 counts[1]--; 35 if(dfs(counts, sb)) { 36 ans = sb.toString(); 37 return true; 38 } 39 sb.deleteCharAt(sb.length() - 1); 40 counts[1]++; 41 } 42 //both options are explored with no right answer, return false to backtrack 43 return false; 44 } 45 }
Solution 2. Greedy
Solution 1 is very inefficient in finding any correct answer. It is suited for finding all possible correct answers. We can use the following greedy algorithm.
At any step, pick the more common character as long as it does not generate subtring aaa or bbb. If the previous two characters are both a, then we have to pick b, vice versa.
The runtime is O(A + B) with space complexity of O(A + B) as well. This greedy algorithm is correct since there is at least one correct answer. Even if we loose the problem condition to possibly not have any right answers, this algorithm will still work with a small modification. For a and b, if max(count(a), count(b)) > (1 + min(count(a), count(b))) * 2, there would be no right answers.
1 class Solution { 2 public String strWithout3a3b(int A, int B) { 3 StringBuilder sb = new StringBuilder(); 4 while(A > 0 || B > 0) { 5 if(sb.length() < 2 || sb.charAt(sb.length() - 1) != sb.charAt(sb.length() - 2)) { 6 if(A >= B) { 7 sb.append(‘a‘); 8 A--; 9 } 10 else { 11 sb.append(‘b‘); 12 B--; 13 } 14 } 15 else if(sb.charAt(sb.length() - 1) == ‘a‘) { 16 sb.append(‘b‘); 17 B--; 18 } 19 else { 20 sb.append(‘a‘); 21 A--; 22 } 23 } 24 return sb.toString(); 25 } 26 }
[LeetCode 984] String Without AAA or BBB
标签:explore exp time tput ice sts poi new available
原文地址:https://www.cnblogs.com/lz87/p/10357293.html