Computer Science & Engineering: Department of
Computer Science & Engineering: Department of
Experiment-3.3
Student Name: SAMBIT
YashikaKUMAR
Khatri PATHY UID: 21BCS2479
21BCS2396
Branch: BE-CSE Section: 642-B
Subject Name: AP Lab Subject Code: 21CSP-351
Aim:
• Decode ways
• Scramble String
Algorithm:
A. Decode ways
1. Check if the input string s is empty or starts with '0'. If so, return 0 because a valid
decoding is not possible.
2. Initialize a dynamic programming array dp of size n + 1, where n is the length of
the input string. Set dp[0] and dp[1] to 1, as there is one way to decode an empty
string and a string of length 1.
3. Iterate through the string starting from index 2 up to n + 1.
Convert the current one-digit and two-digit substrings to integers.
4. If the one-digit substring is not '0', update dp[i] by adding dp[i - 1] because we can
consider the current digit as a single character.
5. If the two-digit substring is between 10 and 26 (inclusive), update dp[i] by adding
dp[i - 2] because we can consider the current two digits as a single character.
B. Scramble strings:
• We will first check the base cases i.e., if the two strings are equal or not or if they
are of different sizes.
• Then, we will create a key for the current problem by concatenating the two
strings and storing it in a dictionary to avoid repeated computations.
• We will iterate over all possible splits of the current string and check whether we
need to swap the left and right substrings or not.
• We will then make recursive calls on these two substrings and return true if any of
the calls return true.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Code(A):
class Solution {
public:
int numDecodings(string s) {
if (s[0] == '0') {
return 0;
}
int n = s.length();
vector<int> dp(n + 1, 0);
dp[0] = dp[1] = 1;
Code(B):
class Solution {
public:
bool isScramble(string s1, string s2) {
unordered_map<string,bool> mp;
int n = s1.size();
if(s2.size()!=n)
return false;
if(s1==s2)
return true;
if(n==1)
return false;
&&
isScramble(s1.substr(i),s2.substr(0,n-i))
);
if(withswap)
return true;
}
return mp[key] = false;
}
};
Output(A):
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Output(B):
Time Complexity :
A. O(n)
B. O(n^4)