Java solution considering continuous "D" or "I"


  • 0
    Y
    public class Solution {
        public int[] findPermutation(String s) {
            if (s == null || s.length() == 0)
                return null;
            
            int n = s.length();
            int[] res = new int[n + 1];
            res[0] = 1;
            helper(s, res, 0);
            return res;
        }
    
        void helper(String s, int[] res, int index) {
            if (index == s.length()) return;
    
            if (s.charAt(index) == 'D') {
                    int i = index;
                    while (i < s.length() && s.charAt(i) == 'D')
                            i++;
                    i--;
                    int first = i + 2;
                    for (int j = index; j <= i + 1; j++)
                            res[j] = first--;
                    index = i + 1;
            } else {
                    int i = index;
                    while (i < s.length() && s.charAt(i) == 'I')
                            i++;
                    i--;
                    int first = index + 2;
                    for (int j = index + 1; j <= i + 1; j++)
                            res[j] = first++;
                    index = i + 1;
            }
            helper(s, res, index);
    
        }
    
    }
    

Log in to reply
 

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