[LeetCode] Check If String Is Transformable With Substring Sort Operations

1585. Check If String Is Transformable With Substring Sort Operations

Given two strings s and t, transform string s into string t using the following operation any number of times:

  • Choose a non-empty substring in s and sort it in place so the characters are in ascending order.
  • For example, applying the operation on the underlined substring in “14234” results in “12344”.

Return true if it is possible to transform s into t. Otherwise, return false.

A substring is a contiguous sequence of characters within a string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
bool isTransformable(string s, string t) {
queue<int> q[10];
int n = s.length();
for(int i = 0; i < n; i++) {
q[s[i]-'0'].push(i);
}
for(int i = 0; i < n; i++) {
int idx = t[i] - '0';
if(q[idx].empty()) return false;
for(int i = 0; i < idx; i++) {
if(q[i].empty()) continue;
if(q[i].front() < q[idx].front()) return false;
}
q[idx].pop();
}
return true;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/26/PS/LeetCode/check-if-string-is-transformable-with-substring-sort-operations/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.