order
This article mainly records leetcode The length of the last word
subject
Given a space that contains only uppercase and lowercase letters ' ' String s, Returns the length of its last word . If the string scrolls from left to right , So the last word is the last word .
If there is no last word , Please return 0 .
explain : A word is made up of only letters 、 Without any space characters Maximum substring .
Example :
Input : "Hello World"
Output : 5
source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/length-of-last-word
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .
Answer key
class Solution {
public int lengthOfLastWord(String s) {
int result = 0;
char[] chars = s.toCharArray();
for (int i= s.length()-1; i >=0; i--) {
if (chars[i] != ' ') {
result++;
continue;
}
if (result != 0) {
return result;
}
}
return result;
}
}
Summary
Here we traverse the string array from back to front , Cumulative length of non space encountered , In case of space, judge whether the result is 0, Not for 0 Returns the result .