484. Find Permutation

题目链接:
https://leetcode.com/problems...

greedy,用一个point:number来指向现在到的数,每次碰到"D",就count"D"的数量,最后碰到I把number + count到number放入结果,更新count = 0。

public class Solution {
    public int[] findPermutation(String s) {
        int n = s.length();
        // the value in result
        int number = 1;
        int count = 0;
        int[] result = new int[n + 1];
        for(int i = 0; i <= n; i++) {
            if(i == n || s.charAt(i) == 'I') {
                for(int j = i; j >= i - count; j--) result[j] = number++;
                count = 0;
            }
            else count++;
        }
        
        return result;
    }
}

还有一种写法是先赋值,之后检查"D",再reverse。

public class Solution {
    public int[] findPermutation(String s) {
        int n = s.length();
        
        int[] result = new int[n + 1];
        // assign value
        for(int i = 0; i <= n; i++) result[i] = i + 1;
        // reverse for D
        for(int i = 0; i < n; i++) {
            if(s.charAt(i) == 'D') {
                int j = i + 1;
                while(j < n && s.charAt(j) == 'D') j++;
                reverse(result, i, j);
                i = j;
            }
        }
        return result;
    }
    
    private void reverse(int[] result, int i, int j) {
        while(i < j) {
            int temp = result[i];
            result[i] = result[j];
            result[j] = temp;
            i++; j--;
        }
    }
}

lulouch13
13 声望6 粉丝