[LeetCode] Construct Smallest Number From DI String

2375. Construct Smallest Number From DI String

You are given a 0-indexed string pattern of length n consisting of the characters ‘I’ meaning increasing and ‘D’ meaning decreasing.

A 0-indexed string num of length n + 1 is created using the following conditions:

  • num consists of the digits ‘1’ to ‘9’, where each digit is used at most once.
  • If pattern[i] == ‘I’, then num[i] < num[i + 1].
  • If pattern[i] == ‘D’, then num[i] > num[i + 1].

Return the lexicographically smallest possible string num that meets the conditions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
bool match(string& s, string& p) {
for(int i = 0; i < p.length(); i++) {
if(p[i] == 'I') {
if(s[i] > s[i+1]) return false;
}
if(p[i] == 'D') {
if(s[i] < s[i+1]) return false;
}
}
return true;
}
public:
string smallestNumber(string pattern) {
string perm = "123456789";
string res = "9999999999";
do {
if(match(perm, pattern)) {
res = min(res,perm.substr(0,pattern.length() + 1));
}
}while(next_permutation(begin(perm),end(perm)));
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/14/PS/Codeforces/construct-smallest-number-from-di-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.