02. Extra Characters in a String
The problem can be found at the following link: Question Link
My Approach
Firstly we'll create a dp array to store immediate results which will be minExtra chars at a particular index.
Create a map of words in dictionary.
Now call a solve function.
In the solve function-
If
indexis equal to size of the string, return 0 since we've completed our taskif
dp[index] != -1we've already calculated our answer for this index so returndp[index]Now, create a empty string
currStr, this will store string formed till current indexminExtrastores the minimum size of extra chars requiredIterate from
cutIdx = 0tos.size()and push the current character into our empty string.Now check if our currString is present in map or not, if it is our currExtra will be 0 , since no extra chars required, else it will be
currStr.size().In
nextExtrawe're finding extra chars in the string that will be formed after the current string i.e from indexcutIndex + 1 to s.size().totalExtrawill be sum of the two calculate extras, i.e current and next.minExtra would store the minimum of all totalExtras.
At last we return
dp[index] = minExtra, here we are basically assigning minExtra todp[index]and at the same time returningdp[index].
Time and Auxiliary Space Complexity
Time Complexity:
O(n)Auxiliary Space Complexity:
O(n)
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star to the rishabhv12/Daily-Leetcode-Solution repository.
Last updated
Was this helpful?