PHP string matching algorithm of the increase or decrease

Given containing only "I" (increase) or "D" (reduce) the string S, so that N = S.length.

Back [0, 1, ..., N] such that any arrangement A for all i = 0, ..., N-1, are:

If S [i] == "I" , then A [i] <A [i + 1]
If S [i] == "D" , then A [i]> A [i + 1]
 

Example 1:

Output: "IDID"
Output: [0,4,1,3,2]
Example 2:

Output: "III"
Output: [0,1,2,3]
Example 3:

Output: "DDI"
Output: [3,2,0,1]
 

prompt:

. 1 <= s.length <= 1000
S includes only the characters "I" or "D".

Source: stay button (LeetCode)

class Solution {

    /**
     * @param String $S
     * @return Integer[]
     */
    function diStringMatch($S) {
        $arr = [];
        $m = 0;
        $n = strlen($S);
        for ($i = 0;$i <= strlen($S);$i++) {
            if ($S[$i] == 'I') {
                $arr[]=$m; //array_push($arr,$m);
                $m ++;
            } else {
                $arr[]=$n;
                $n --;
            }
        }
        return $arr;
    }
}

Guess you like

Origin www.cnblogs.com/corvus/p/11985973.html
Recommended