[Swift]LeetCode984. 不含 AAA 或 BBB 的字符串 | String Without AAA or BBB

原文地址:http://www.javashuo.com/article/p-sppmqity-md.html html

Given two integers A and B, return any string S such that:spa

  • S has length A + B and contains exactly A 'a' letters, and exactly B 'b' letters;
  • The substring 'aaa' does not occur in S;
  • The substring 'bbb' does not occur in S

Example 1:code

Input: A = 1, B = 2 Output: "abb" Explanation: "abb", "bab" and "bba" are all correct answers. 

Example 2:htm

Input: A = 4, B = 1 Output: "aabaa" 

Note:blog

  1. 0 <= A <= 100
  2. 0 <= B <= 100
  3. It is guaranteed such an S exists for the given A and B.

給定兩個整數 A 和 B,返回任意字符串 S,要求知足:字符串

  • S 的長度爲 A + B,且正好包含 A 個 'a' 字母與 B 個 'b' 字母;
  • 子串 'aaa' 沒有出如今 S 中;
  • 子串 'bbb' 沒有出如今 S 中。 

示例 1:get

輸入:A = 1, B = 2
輸出:"abb"
解釋:"abb", "bab" 和 "bba" 都是正確答案。

示例 2:input

輸入:A = 4, B = 1
輸出:"aabaa" 

提示:string

  1. 0 <= A <= 100
  2. 0 <= B <= 100
  3. 對於給定的 A 和 B,保證存在知足要求的 S

12msit

 1 class Solution {
 2     func strWithout3a3b(_ A: Int, _ B: Int) -> String {
 3         var A = A
 4         var B = B
 5         var ret:[Character] = [Character](repeating:" ",count:A+B)
 6         for i in 0..<ret.count
 7         {
 8             if i >= 2 && ret[i-1] == ret[i-2]
 9             {
10                 if ret[i-1] == "a"
11                 {
12                     ret[i] = "b"
13                     B -= 1
14                 }
15                 else
16                 {
17                     ret[i] = "a"
18                     A -= 1
19                 }
20             }
21             else
22             {
23                 if A > B
24                 {
25                     ret[i] = "a"
26                     A -= 1
27                 }
28                 else
29                 {
30                     ret[i] = "b"
31                     B -= 1
32                 }
33             }            
34         }
35         return String(ret.reversed())
36     }
37 }
相關文章
相關標籤/搜索