LeetCode 3481: Apply Substitutions Solution
Master LeetCode problem 3481 (Apply Substitutions), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
3481. Apply Substitutions
Problem Explanation
Explanation:
Given a string s and a list of substitutions substitutions, where each substitution is represented as a string in the format "abc->def", we are required to apply the substitutions to the string s iteratively until no more substitutions can be made.
To solve this problem, we can use a stack to keep track of the characters in the string s. We iterate over each character in the string s. For each character, we check if it is part of any substitution in the substitutions list. If it is part of a substitution, we push the corresponding replacement characters onto the stack. If it is not part of any substitution, we simply push the character onto the stack.
After processing all characters in the string s, we concatenate the characters in the stack to form the final substituted string.
:
Solution Code
import java.util.*;
class Solution {
public String applySubstitutions(String s, List<String> substitutions) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
boolean substituted = false;
for (String substitution : substitutions) {
if (substitution.charAt(0) == c) {
substituted = true;
for (char replacement : substitution.substring(3).toCharArray()) {
stack.push(replacement);
}
break;
}
}
if (!substituted) {
stack.push(c);
}
}
StringBuilder sb = new StringBuilder();
for (char c : stack) {
sb.append(c);
}
return sb.toString();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3481 (Apply Substitutions)?
This page provides optimized solutions for LeetCode problem 3481 (Apply Substitutions) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3481 (Apply Substitutions)?
The time complexity for LeetCode 3481 (Apply Substitutions) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3481 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3481 in Java, C++, or Python.