22(June) Extract the Number from the String
22. Extract the Number from the String
The problem can be found at the following link: Question Link
Problem Description
Given a sentence containing several words and numbers, find the largest number among them which does not contain the digit '9'. If no such number exists, return -1.
Examples:
Input:
sentence = "This is alpha 5057 and 97"Output:
5057Explanation: 5057 is the only number that does not contain a 9.
My Approach
Initialization:
Initialize
numto -1 to keep track of the largest valid number.Initialize
currentNumto 0 for constructing numbers from the string.Use boolean flags
validNumandhasDigitto track if the current number is valid and if there are digits being processed.
Parsing the String:
Iterate through each character in the sentence.
If the character is a digit:
Set
hasDigitto true.Check if the digit is greater than 8; if so, mark
validNumas false.Accumulate the digit to
currentNum.
If the character is not a digit:
If a number has been constructed (
hasDigitis true) and it is valid (validNumis true) and greater than the current largest number (num), updatenum.Reset
currentNum,validNum, andhasDigitfor the next potential number.
Final Check:
After the loop, perform a final check to consider the last constructed number.
Return:
Return the largest valid number found, or -1 if no valid number exists.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where (n) is the length of the sentence, as we iterate through each character of the string.
Expected Auxiliary Space Complexity: O(n), as we only use a constant amount of additional space for variables.
Code (C++)
Code (Java)
Code (Python)
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated