Hi all,
I think that i've solved Leetcode 58, and it seems like my algorithm makes sense, but I keep running into a runtime error, I was hoping to get some help with this.
My algorithm is as follows:
Initialized a variable to store the length of the last word. This variable will be iteratively updated as we traverse the string (backwards). This is the value that will be returned when the algorithm has completed.
Initialize a variable to 'point' to the last character of the string. This pointer will be moved and used as the reference to determine whether the current character in the string being pointed to is a space or an actual character that should be accounted for in our word length variable.
Begin looping from the end of the string, checking for any spaces and decrementing the 'pointer' if a space is found. This moves the pointer left until the first non-space character of the string is found. Once the pointer has advanced left to the first non-space character, exit the loop. The problem is now set-up to be solved normally. This first loop is to address the edge-case of having trailing spaces on our input string.
Next, begin looping again from where we left off after accounting for any trailing spaces, but this time checking whether the character currently being iterated on is a non-space character or not. If the character is a non-space character, increment the length of the last word variable, and move the pointer one position to the left. If the character currently being iterated on is a space, we can conclude that we've counted all the character of the last word in the string, exit the loop and return the length of the last word value.
On paper this algorithm seems to work fine. O(n) time as well. However, Leetcode doesn't want to accept my code. Could anyone lend me a hand here? I'm not sure where i'm going wrong. Thanks! Code below for reference.
class Solution {public int lengthOfLastWord(String s) {
int wordLen = 0;
int i = s.length() - 1;
while(s.charAt(i) == (' ')){
i--;
}
while(s.charAt(i) != (' ')){
wordLen ;
i--;
}
return wordLen;
}
}
Edit: Sorry for the horrible readability of my code. I'm not sure how to indent code on Reddit.
Subreddit
Post Details
- Posted
- 2 years ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/leetcode/co...