[LeetCode-interview algorithm classic-Java implementation] [058-Length of Last Word (Length of the Last Word)], leetcode -- java

Source: Internet
Author: User

[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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.