You are given an array of n elements [1,2,....n]. For example {3,2,1,6,7,4,5}.
Now we create a signature of this array by comparing every consecutive pir of elements. If they increase, write I else write D. For example for the above array, the signature would be "DDIIDI". The signature thus has a length of N-1. Now the question is given a signature, compute the lexicographically smallest permutation of [1,2,....n]. Write the below function in language of your choice.
vector* FindPermute(const string& signature);
-----------------------------------------------------------------------------------------------
When meeting some 'I', we could get back to previousLow(the position of previous 'I'), the elements between previous 'I' and current 'I' are decreasing...
找到I就可以填数了,然后回填之前的D
#include<stdio.h>
#include<string>
#include<vector>
using namespace std;
class Solution {
public:
vector<int> solve(const string& input) {
int len = input.length(), i, j, element = 1, previousLow = -1;
vector<int> res(len + 1, 0);
for (i = 0; i <= len; ++i) {
if (input[i] == 'I' || i == len) {
for (j = i; j > previousLow; --j)
res[j] = element++;
previousLow = i;
}
}
return res;
}
};
int main()
{
Solution s = Solution();
vector<int> res1 = s.solve("DDIIDI"); //3214657
vector<int> res2 = s.solve("DDDDDI"); //6543217
vector<int> res3 = s.solve("DDDDDD"); //7654321
vector<int> res4 = s.solve("IIIIII"); //1234567
vector<int> res5 = s.solve("IIIDDD"); //1237654
vector<int> res6 = s.solve("DDDIII"); //4321567
return 0;
}
Python Version:
class Solution:
def diStringMatch(self, S):
l = len(S)
res = [0 for i in range(l + 1)]
prevI, cur = -1, 0
for i in range(l + 1):
if (i == l or S[i] == 'I'):
res[i] = cur
cur += 1
for j in range(i-1, prevI, -1):
res[j] = cur
cur += 1
prevI = i
return res
s = Solution()
print(s.diStringMatch("DDI"))
Could submit it in Leetcode https://leetcode.com/problems/di-string-match/submissions/