Given a string s
consists of some words separated by spaces, return the length of the last word in the string. If the last word does not exist, return 0
.
A word is a maximal substring consisting of non-space characters only.
Example 1:
Input: str="Hello Words "
Output: 5
Approach:
Java
public class LengthofLastWord {public static void main(String[] args) {String str = "Hello Words ";int length = lengthOfLastWord(str);System.out.println("Length is " + length);}// Method to find last word lengthpublic static int lengthOfLastWord(String s) {int length = 0;for (int i = s.length() - 1; i >= 0; i--) {// after start letter not character, then return lengthif (length > 0 && !Character.isLetter(s.charAt(i))) {return length;}// if found letter then increase countif (Character.isLetter(s.charAt(i))) {length++;}}return length;}}
C++
#include <bits/stdc++.h>using namespace std;//function to find last word lengthint lengthOfLastWord(string s){int length = 0;for (int i = s.length() - 1; i >= 0; i--) {// after start letter not character, then return lengthif (length > 0 && s[i]==' ') {return length;}// if found letter then increase countif (s[i]!=' ') {length++;}}return length;}int main(){string str = "Hello Words ";int length = lengthOfLastWord(str);cout<<"Length is "<<length;return 0;}
No comments:
Post a Comment