根据模式串构造最小数字
难度:
标签:
题目描述
代码结果
运行时间: 24 ms, 内存: 15.9 MB
/*
* Problem Description:
* Given a pattern string containing 'I' (increase) and 'D' (decrease),
* construct the smallest lexicographical permutation of numbers '1' to '9'
* such that for every 'I' in the pattern, the corresponding numbers in the result
* are increasing, and for every 'D', they are decreasing.
*
* Approach (using Java Streams):
* 1. Create a list of integers from 1 to 9.
* 2. Use a Deque to manage the sequence according to 'I' and 'D' pattern.
* 3. Iterate through the pattern and modify the Deque accordingly.
* 4. Convert the Deque to a string and return the result.
*/
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class SolutionStream {
public String smallestNumber(String pattern) {
List<Integer> numbers = IntStream.rangeClosed(1, 9).boxed().collect(Collectors.toList());
Deque<Integer> deque = new LinkedList<>();
for (int i = 0; i <= pattern.length(); i++) {
deque.offerLast(numbers.get(i));
if (i == pattern.length() || pattern.charAt(i) == 'I') {
while (!deque.isEmpty()) {
deque.pollFirst();
}
}
}
return deque.stream().map(String::valueOf).collect(Collectors.joining());
}
}
解释
方法:
该题解采用逐步构建方法,通过遍历模式字符串`pattern`,逐个添加数字到结果列表`ans`中,并根据字符是'I'还是'D'决定如何处理。对于字符'I',直接在结果列表末尾添加当前数字。对于字符'D',同样在末尾添加当前数字,然后从当前位置向前遍历,如果前一个字符也是'D',则将当前数字与前一个数字交换,直到遇到不是'D'的情况或者到达列表开头。最后,将数字列表转换为字符串形式返回。
时间复杂度:
O(n^2)
空间复杂度:
O(n)
代码细节讲解
🦆
题解中的算法在处理连续的'D'字符时,为什么选择使用从后向前的单次遍历和交换方法?这种方法是否能保证在所有情况下都正确生成满足要求的数字序列?
▷🦆
算法使用的交换机制是否会导致在某些特定的pattern输入下,如'IDDD'或'DDID',生成的数字序列不是最小可能的序列?
▷🦆
在题解算法中,初始数字设置为1,随后逐次增加,这种处理方式是否可能导致在处理长字符串时超出数字'9'的限制?
▷