An encoded string S is given. To find and write the decoded string to a tape, the encoded string is read one character at a time and the following steps are taken:
If the character read is a letter, that letter is written onto the tape.
If the character read is a digit (say d), the entire current tape is repeatedly written d-1 more times in total.
Now for some encoded string S, and an index K, find and return the K-th letter (1 indexed) in the decoded string.
Example 1:
Input: S = “leet2code3”, K = 10
Output: “o”
Explanation:
The decoded string is “leetleetcodeleetleetcodeleetleetcode”.
The 10th letter in the string is “o”.
Example 2:
Input: S = “ha22”, K = 5
Output: “h”
Explanation:
The decoded string is “hahahaha”. The 5th letter is “h”.
Example 3:
Input: S = “a2345678999999999999999”, K = 1
Output: “a”
Explanation:
The decoded string is “a” repeated 8301530446056247680 times. The 1st letter is “a”.
Note:
- 2 <= S.length <= 100
- S will only contain lowercase letters and digits 2 through 9.
- S starts with a letter.
- 1 <= K <= 10^9
- The decoded string is guaranteed to have less than 2^63 letters.
分析:
- 这道题是把字符串按照给定的规则展开,然后返回展开后的字符串的第K个字符,应该要怎么思考呢?
- 我不知道大家注意到note的第5点没有,为什么他在这里突然加这么一点,告诉我们长度小于2^63,其实就是在暗示我们要用到总长度(因为我们不可能真把展开后的字符串写出来)
- 然后这里的测试样例也有点迷惑作用,因为他故意不给出最后以字符结尾的例子,就是担心把思路直接暴露出来了,我们来看一个例子
- S = ‘leet2code3problem’,这个字符串展开后总长度为43,’problem’是没有重复的部分,前面’leet2code3’总长度是36,那么假设此时K = 37,38,39…,43,我们可以直接得出答案。那如果K小于37呢,那么问题是不是可以转换成在S=’leet2code3’求第K个字符(多余的部分可以直接不要)
- 当以数字结尾时,那么整个字符串就是S[:-1]的若干次重复,例如此时S=’leet2code3’的长度为36,设K=18吧,那么基本字符串的长度应该为36/3=12,那么我们要求的字符应该是第18%12=6个字符,现在问题转换成了S=’leet2code’,K=6,又变成我们第4点中分析的情况了,依次类推即可
思路:
- 分析过程很简单明了,但是代码却不太好写,比较繁杂
- 我们先去找S中最后一个数字的位置,然后判断K是不是处于这个数字后面的那串字符串中(关键),若是则直接返回
- 若不是则改变S,K的值,注意了我们的总长度不能每次改变一次S重新计算一次,那样太麻烦了(不过我猜应该不会超时,因为s长度不超过100),而是每次通过减去多余字符串的长度和除以结尾数字来改变!!!
1 | class Solution(object): |