Length of Last Word | LeetCode problem 58

preview_player
Показать описание
Length of Last Word
Leetcode problem number 58
Solution in JAVA

JAVA interview programming playlist:

#java #interviewquestions #leetcode
Рекомендации по теме
Комментарии
Автор

good explanation
here is my code without using trim() method
class Solution {
public int lengthOfLastWord(String s) {
int count=0;
if(s==null|| s.length()==0) return 0;
int i = s.length()-1;
while(i>=0 && s.charAt(i)==' ')
{
i--; // we are skiping the end(tail) spaces

}
while(i>=0 && s.charAt(i)!=' ')
{
count++;
i--;
}
return count;
}
}

chakravarthybatna
Автор

Every Queen need a crown and here is your crown 👑

aasheesh
Автор

class Solution {
public int lengthOfLastWord(String s) {
int i=s.length()-1;
int count=0;
for (;i>=0;i--){
if (s.charAt(i)==' ') continue;
else break;
}

for (;i>=0;i--){
if (s.charAt(i)!=' '){
count+=1;
}
else break;
}

return count;
}
}

minhhoangcong
Автор

trim may not work;
as an alternate we can write replace break; with

else{
if(count>0)
return count;
}

jagratsahoo
Автор

public int LengthOfLastWord(string s) {

// remove heading and trailing spaces from string
// split string to whilespaces
string[] strArray = s.Trim().Split(' ');

// get last items of string array
return
}
Runtime: 46 ms, faster than 91.33% of C# online submissions for Length of Last Word.

sachinpatil
Автор

Madam please add some more question to the playlist

PallabChatterjee
Автор

String st-" Hello world leet. ";
String [] str=st.split("\\s");
SOP(str[str.length-1]. length ());
Is this correct, instead of reverse and break please share your thoughts

automationanywhere
Автор

Can you share the git repo for the codes which you do

nirmalchakraborty
Автор

class Solution {
public int lengthOfLastWord(String s) {
int c=0, k=0;
for(int i=s.length()-1;i>=0;i--)
{
if(s.charAt(i)==' ')
c++;
else
break;


}
for(int i=s.length()-1-c;i>=0;i--)
{
if(s.charAt(i)==' ')
break;
else
k++;
}
return k;
}
}

dljogjl