58. Length of the last word
Given a string s containing only uppercase and lowercase letters and Spaces’ ‘, return the length of its last word. If the string scrolls from left to right, the last word is the last word to appear.
If the last word does not exist, return 0.
Note: A word is the largest substring that consists of only letters and does not contain any space characters.
Example:
Input:"Hello World"
Output: 5
Copy the code
Ideas:
- String traversal
- There are two main cases of traversing from the end of the string
- First case: as a string”
Hello Word"
For example, iterate from back to front until you reach the end of the loop or encounter a space, which is the last word"Word"
Length of 5. - The second case: a string
"Hello Word "
For example, you need to filter out the trailing whitespace before performing the operation in the first case, which considers the length of the last Word” Word” to be 5.
- First case: as a string”
- Therefore, the complete process is as follows: filter out the space from the back to find the tail of the word, then traverse forward from the tail to find the head of the word, and finally subtract the two, which is the length of the word.
- Time complexity: O(n), where n is the total length of the trailing space and the trailing word.
Reference Code 1:
class Solution {
public int lengthOfLastWord(String s) {
if (s == null || s.length() == 0) {
return 0;
}
int end = s.length() - 1;
while (end >= 0 && s.charAt(end) == ' ') {
end--;
}
if (end < 0 ) return 0;
int start = end;
while (start >= 0&& s.charAt(start) ! =' ') {
start--;
}
return end - start;
}
}
Copy the code
Other reference codes
Use the Java language itself to provide the function implementation
class Solution {
public int lengthOfLastWord1(String s) {
if (s == null || s.length() == 0) {
return 0;
}
String[] strs = s.split("");
if (strs.length > 0) {
return strs[strs.length - 1].length();
} else {
return 0;
}
}
public int lengthOfLastWord2(String s) {
if (s == null || s.length() == 0) {
return 0;
}
s = s.trim();
int start = s.lastIndexOf("") + 1;
return s.substring(start).length();
}
public int lengthOfLastWord3(String s) {
if (s == null || s.length() == 0) {
return 0;
}
s = s.trim();
return s.length() - 1 - s.lastIndexOf("");
}
}
Copy the code
Some pictures from the network, copyright to the original author, delete.Copy the code