CareerCup the Lexicographically Smallest Permutation DI序列字典序最小 LeetCode 942. DI String Match

265 篇文章 1 订阅

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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值