A string x is called almost equal to y if you can change at most one character in x to make it identical to y.
A sequence of indices seq is called valid if:
The indices are sorted in ascending order.
Concatenating the characters at these indices in word1 in the same order results in a string that is almost equal to word2.
Return an array of size word2.length representing the lexicographically smallest valid sequence of indices. If no such sequence of indices exists, return an empty array.
Note that the answer must represent the lexicographically smallest array , not the corresponding string formed by those indices.
Input: word1 ="aaaaaa", word2 ="aaabc"Output: []Explanation:
There is no valid sequence of indices.#### Example 4Input: word1 ="abc", word2 ="ab"Output: [0,1]
To form a string almost equal to word2 by picking indices from word1, we want the lexicographically smallest sequence. This means always picking the smallest possible index for each character, allowing at most one mismatch (where we can change a character to match word2).
classSolution {
publicint[]smallestValidSequence(String word1, String word2) {
int n = word1.length(), m = word2.length();
List<Integer> ans =new ArrayList<>();
int changes = 0, i = 0, j = 0;
while (i < n && j < m) {
if (word1.charAt(i) == word2.charAt(j)) {
ans.add(i); i++; j++;
} elseif (changes == 0) {
ans.add(i); i++; j++; changes++;
} else {
i++;
}
}
if (j == m && changes <= 1) {
return ans.stream().mapToInt(x -> x).toArray();
}
returnnewint[0];
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
funsmallestValidSequence(word1: String, word2: String): IntArray {
val n = word1.length; val m = word2.length
val ans = mutableListOf<Int>()
var changes = 0; var i = 0; var j = 0while (i < n && j < m) {
if (word1[i] == word2[j]) {
ans.add(i); i++; j++ } elseif (changes ==0) {
ans.add(i); i++; j++; changes++ } else {
i++ }
}
returnif (j == m && changes <=1) ans.toIntArray() else intArrayOf()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
defsmallest_valid_sequence(word1: str, word2: str) -> list[int]:
n, m = len(word1), len(word2)
ans: list[int] = []
changes =0 i = j =0while i < n and j < m:
if word1[i] == word2[j]:
ans.append(i)
i +=1; j +=1elif changes ==0:
ans.append(i)
i +=1; j +=1 changes +=1else:
i +=1if j == m and changes <=1:
return ans
return []
impl Solution {
pubfnsmallest_valid_sequence(word1: String, word2: String) -> Vec<i32> {
let n = word1.len();
let m = word2.len();
let w1 = word1.as_bytes();
let w2 = word2.as_bytes();
letmut ans =vec![];
let (mut i, mut j, mut changes) = (0, 0, 0);
while i < n && j < m {
if w1[i] == w2[j] {
ans.push(i asi32); i +=1; j +=1;
} elseif changes ==0 {
ans.push(i asi32); i +=1; j +=1; changes +=1;
} else {
i +=1;
}
}
if j == m && changes <=1 { ans } else { vec![] }
}
}