Magical String

A magical string S consists of only '1' and '2' and obeys the following rules:

The string S is magical because concatenating the number of contiguous occurrences of characters '1' and '2' generates the string S itself.

The first few elements of string S is the following: S = "1221121221221121122……"

If we group the consecutive '1's and '2's in S, it will be:

1 22 11 2 1 22 1 22 11 2 11 22 ......

and the occurrences of '1's or '2's in each group are:

1 2 2 1 1 2 1 2 2 1 2 2 ......

You can see that the occurrence sequence above is the S itself.

Given an integer N as input, return the number of '1's in the first N number in the magical string S.

Note: N will not exceed 100,000.

Example 1:

Input: 6
Output: 3
Explanation: The first 6 elements of magical string S is "12211" and it contains three 1's, so return 3.

 1 public class Solution {
 2     public int magicalString(int n) {
 3         if (n <= 0) return 0;
 4         if (n < 4) return 1;
 5         
 6         int[] magical = new int[n];
 7         magical[0] = 1; magical[1] = magical[2] = 2;
 8         
 9         int result = 1;
10         int start = 2, end = 2;
11         while (start < n) {
12             if (magical[start] == 1) {
13                 if (end + 1 < n)
14                     magical[end + 1] = magical[end] == 1 ? 2 : 1;
15                 
16                 end++;
17                 result += 1;
18             } else {
19                 if (end + 2 < n) 
20                     magical[end + 2] = magical[end] == 1 ? 2 : 1;
21                 if (end + 1 < n)
22                     magical[end + 1] = magical[end] == 1 ? 2 : 1;
23                 end += 2;
24             }
25             start++;
26         }
27         return result;
28     }
29 }
原文地址:https://www.cnblogs.com/amazingzoe/p/6439718.html