[LeetCode-interview algorithm classic-Java implementation] [058-Length of Last Word (Length of the Last Word)], leetcode -- java
[058-Length of Last Word (Length of the Last Word )][LeetCode-interview algorithm classic-Java implementation] [directory indexes for all questions]Original question
Given a string s consists of upper/lower-case alphabets and empty space characters' '
, Return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
For example,
Given s ="Hello World"
,
Return5
.
Theme
Returns the length of the last word in a string consisting of uppercase and lowercase letters and spaces.
Solutions
First, find the position x of the first letter. If it is not found, return 0. If it is found, record the position of the first space as y (y may be-1, returns x-y.
Code Implementation
Algorithm Implementation class
Public class Solution {public int lengthOfLastWord (String s) {int index = s. length ()-1; // find the first character not ''from the back while (index> = 0 & s. charAt (index) = '') {index --;} if (index <0) {return 0;} int tmp = index; // The execution below indicates that the last word exists. // find the first ''character while (index> = 0 & s. charAt (index )! = '') {Index --;} return tmp-index ;}}
Evaluation Result
Click the image. If you do not release the image, drag it to a position. After the image is released, you can view the complete image in the new window.
Note
Please refer to the source for reprinting [http://blog.csdn.net/derrantcm/article/details/47164433]
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.