栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Lintcode 1890 · Form Minimum Number [Python]

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Lintcode 1890 · Form Minimum Number [Python]

Description
Given a pattern str containing only I and D. I for increasing and D for decreasing. Please design an algorithm to return the string that conforms to the pattern and has the smallest dictionary order. Digits from 1 to 9 and digits can’t repeat.

Example
Example 1:

Input:
“D”
Output:
“21”
Explanation:
2>1
Example 2:

Input:
“II”
Output:
“123”
Explanation:
1<2<3
Example 3:

Input:
“DIDI”
Output:
“21435”
Example 4:

Input:
“DDIDDIID”
Output:
“321654798”

题目不难,其数字不重复,其实降低了(思考)复杂度。观察“DIDI”之类的例子,可以知道,每次找到一个I,那从这个I的位置到其左侧最近的I开始,就是一个递减序列。那从哪个数字开始减呢?观察例子可知,这个I如果位于第4位,那从这个I左侧最近的I开始到这个其间最大的数字也就是当前I的位置数,也就是indexof(current I)+ 1,然后,减到少次停下呢?减去当前I到其左侧最近的I的位数。比如两I,相隔2个数字,那就减两次,完成后,更新当下I位置为下一个遇到的I的左侧最近的I位置(LastI)。为了处理方便,一开始就在最后一位加上一个I,方便通用化处理。

class Solution:
    """
    @param str: the pattern 
    @return: the minimum number
    """
    def formMinimumNumber(self, string):
        # Write your code here.
        tempstr = string + 'I'
        curchar = 0
        res = ""
        lastI = 0
        for idx, char in enumerate(tempstr):
            if char == 'I':
                curchar = idx + 1
                while curchar != lastI:
                    res += str(curchar)
                    curchar -= 1
                lastI = idx + 1            
        return res
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/321593.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号