Problem Statement
This problem is from Leetcode – Length of Last Word. The problem statement is as below:
Given a string s consisting of words and spaces, return the length of the last word in the string
Solution
Approach-1
Lets try the most obvious approach first, by using split()
- Take the input String and split on ” “
- This will give us the split array consisting of individual strings. We are interested in the last strings.
- Return the length of the string at last index.
Lets see the code sample below:
/*
* function to compute length of last word
* input string -> String s = "Hello World";
*/
public int lengthOfLastWord(String s) {
int len = 0;
// split on " " to extract individual words out in an array
String[] inputArr = s.split(" ");
// store the length of the last word
len = inputArr[inputArr.length-1].length();
// return this length
return len;
}
This code returns the following output:
Length of last word: 5
You can checkout the code from Github here: Length of Last Word – First Approach
Approach-2
Lets try another approach without using split(). We can traverse the array in reverse direction and count number of characters passed until we encounter space.
Lets see the code sample below:
/*
* function to compute length of last word
* input string -> String s = "Hello World";
*/
public int lengthOfLastWord(String s) {
int len = 0;
// trim the leading and trailing spaces
s = s.trim();
/*
* Iterate the array from last char until a space is encountered
*/
for(int i= s.length()-1; i>=0; i--){
// increment counter if char is encountered
if(s.charAt(i) != ' ') {
len = len+1;
}
// break out of loop when space is encountered
else {
break;
}
}
// return counter
return len;
}
This code produces the output as below:
Length of last word: 5
You can checkout the code from GitHub here: Length of Last Word – Second Approach
See the performance of this approach below: