simple stringbuilder O(n) space in java


  • 0
    S

    hi, I would like to share my solution.
    the trick is keep appending string by looking the st pointer

    
    public class Solution {
        public int magicalString(int n) {
            StringBuilder s = new StringBuilder();
            s.append("122");
            int num = 1;
            int st = 2;
            while (s.length() < n){
                if (s.charAt(st) == '2' && num == 2)
                    s.append("22");
                else if (s.charAt(st) == '2' && num == 1)
                    s.append("11");
                else s.append(num);
                st ++;
                num = num ^ 3;// 1 ^ 3 -> 2, 2 ^ 3 -> 1
            }
            int count =0;
            for (int i =0; i < n; i++){
                if (s.charAt(i) == '1')
                    count ++;
            }
            return count;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.