Extract the Number from the String
JavaView on GFG
Time: O(n)
Space: O(1)
Advertisement
Intuition
Extract all numeric substrings from a string and compute their sum or return them.
Algorithm
- 1Scan: when digit found, collect consecutive digits to form number. Add to result.
Common Pitfalls
- •Handle multi-digit numbers by accumulating. Use isDigit check. Parse each numeric run.
Extract the Number from the String.java
Java
// Approach: Scan string character by character, accumulate digits, parse the resulting number.
// Time: O(n) Space: O(1)
class Solution {
long ExtractNumber(String sentence) {
String arr[] = sentence.split(" ");
long max = -1;
for (String st : arr) {
if (st.charAt(0) - '0' >= 0 && st.charAt(0) - '0' <= 9) {
if (!st.contains("9")) {
long convert = Long.parseLong(st);
if (convert > max)
max = convert;
}
}
}
return max;
}
}Advertisement
Was this solution helpful?