?LeetCode刷題實戰(zhàn)481:神奇字符串

示例? ? ? ? ? ? ? ? ? ? ? ? ?
示例 1:
輸入:n = 6
輸出:3
解釋:神奇字符串 s 的前 6 個元素是 “122112”,它包含三個 1,因此返回 3 。
示例 2:
輸入:n = 1
輸出:1
解題
分為兩個字符串:1表示原始字符串,2表示分組后的字符串
結(jié)合第一個字符串向第二個字符串中添加元素
結(jié)合第二個字符串向第一個字符串中添加元素。
class?Solution?{
????public?int?magicalString(int?n) {
????????if(n <= 0)
????????????return?0;
????????if(n <= 3)
????????????return?1;
????????StringBuilder base?= new?StringBuilder();
????????StringBuilder sub = new?StringBuilder();
????????base.append("122");
????????sub.append("12");
????????int?index = 0;
????????int?temp = 0;
????????int?counts = 1;
????????while?(base.length() < n){
????????????index = sub.length();
????????????temp = base.charAt(index)-'0';
????????????sub.append(temp);
????????????if(temp==2){
????????????????temp = base.charAt(base.length()-1)-'0';
????????????????if(temp == 2){
????????????????????base.append("11");
????????????????????if(base.length() <= n)
????????????????????????counts += 2;
????????????????????else
????????????????????????counts += 1;
????????????????}else?{
????????????????????base.append("22");
????????????????}
????????????}else?{//temp == 1
????????????????temp = base.charAt(base.length()-1)-'0';
????????????????if(temp == 2){
????????????????????base.append("1");
????????????????????counts += 1;
????????????????}else?{
????????????????????base.append("2");
????????????????}
????????????}
????????}
????????return?counts;
????}
}
