【算法】Google笔试题Lexicographically Smallest permutation

lexicographically也就是字典顺序,在文本分析和搜索中有不少应用,比如在查询语句的预处理时,可以通过求得 lexicographic minimum,类似的查询就可以命中缓存,只在排序的时候考虑一下关键词在文档里的距离。

(1)lexicographically smallest permutation 问题

这里看到这个笔试题:

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);

其实这个题目难点在于看不懂题。。。。

理解题意:

{3,2,1,6,7,4,5}的lexicographically smallest permutation为{1,2,3,4,5,6,7}。

要求一个满足"DDIIDI"的lexicographically smallest permutation。

解题思路:

解题方法很简单,碰到D就反转,碰到连续的D就连续反转。

Algorithm:

Step One: Take the permutation 1 2 3 .... n. For example if n=5 take permutation 1 2 3 4 5. Call It original sequence.

Step Two: Mark all the continuous occurrences of D in the given signature.

Step Three: Then for each continuous sequence of D, going from left to right reverse the strip corresponding to that in original sequence.Every time make the new sequence as original sequence.

Example Take the above case. Signature = DDIIDI , take original permutation as 1 2 3 4 5 6 7. Then for first continuous sequence DD reverse the strip 1 2 3 to 3 2 1 hence sequence becomes 3 2 1 4 5 6 7. Then for second sequence D reverse strip 5 6 to 6 5 hence sequence becomes 3 2 1 4 6 5 7. There is no continuous D left we are done and reached the answer. 

 

【TODO】代码实现。

 ------

(2) lexicographic minimum问题:

Write the code to find lexicographic minimum in a circular array, e.g. for the array BCABDADAB, the lexicographic mininum is ABBCABDAD.

解题思路:

- 以k步(k = 0。。。n)移动循环数组,每次看结果是不是最小值,如果是,则退出,否则继续移动。

算法分析:

Given string S.

For String S' = SS (append S to itself).

Compute suffix tree (ST) of S.

Now do a depth first search of ST, picking the children in lexicographic order.

Pick the first node you find, at depth |S|.

Linear time algorithm.

转载于:https://www.cnblogs.com/utopiazh/archive/2013/01/12/2857967.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值