Java [Leetcode 58]length of last Word

Source: Internet
Author: User

Title Description:

Given A string s consists of upper/lower-case alphabets and empty space characters ‘ ‘ , return the length of LA St Word in the string.

If the last word does not exist, return 0.

Note:a word is defined as A character sequence consists for non-space characters only.

For example,
Given S = "Hello World" ,
Return 5 .

Problem Solving Ideas:

First position the string from the forward number to the first non-null character, and then make a judgment.

Read backwards from the first position, and each time a null character is encountered, the counter is zeroed, and then the next count is continued.

The code is as follows:

public class Solution {public    int Lengthoflastword (String s) {    int curlen = 0, len = 0, end =-1;    if (s = = NULL | | (len = s.length ()) = = 0)     return 0;    for (int i = len-1; I >= 0; i--) {    if (S.charat (i)! = ") {    end = i;    break;    }       }    for (int i = 0; I <= end; i++) {    if (S.charat (i)! = ")    curlen++;    else {    Curlen = 0;    }    }    return curlen;}    }

  

Java [Leetcode 58]length of last Word

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.