9. DI String Match
Posted sxuer
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了9. DI String Match相关的知识,希望对你有一定的参考价值。
Title:
Given a string S
that only contains "I" (increase) or "D" (decrease), let N = S.length
.
Return any permutation A
of [0, 1, ..., N]
such that for all i = 0, ..., N-1
:
- If
S[i] == "I"
, thenA[i] < A[i+1]
- If
S[i] == "D"
, thenA[i] > A[i+1]
Example 1:
Input: "IDID"
Output: [0,4,1,3,2]
Example 2:
Input: "III"
Output: [0,1,2,3]
Note:
1 <= S.length <= 10000
S
only contains characters"I"
or"D"
.
Analysis of Title:
If S[i] == "I"
, then A[i] < A[i+1] It means when get a ‘I‘ then in here is a smaller and the next is bigger.
If S[i] == "D"
, then A[i] > A[i+1] In the similar way.
Test case:
"IDID"
Python:
ps: A simple way is "for : If I then get 0,0+1; If D then get len(S),len(S)-1"
But I want to learn another method of deque.
class Solution(object):
def diStringMatch(self, S):
"""
:type S: str
:rtype: List[int]
"""
from collections import deque
table = deque(range(len(S)+1)) #创建双端队列可迭代对象,数据包括 0~len(S)+1
res = []
for s in S:
if s==‘I‘:
res.append(table.popleft()) #若为I,加入左边(小)
else:
res.append(table.pop()) #若为D,加入右边(大)
res.append(table.pop()) #把最后一个加进去,输出比输入多一位
return res
Analysis of Code:
All the analysis is already in the Title.
以上是关于9. DI String Match的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 942. DI String Match 增减DI字符串匹配
LeetCode --- 942. DI String Match 解题报告
LeetCode 942 DI String Match 解题报告
[TIA PORTAL][CONVERT] Convert Char Array to DInt...DInt to Char Array..Useful and easy function(代码片段