Tuesday, September 8, 2015

Length of Last Word

1. Example

s= "Hello World"
return 5( the length of "World")
s= "Hello World "
return 5 (even space happen at the last character)

2. Implementation
Q1: find the last word;
A1: split by space("\\s") and get the last word and return string.length()
split O()
get the last word
Q1: len- last space space, how to find out Space position?
A1: go over all characters and find the last space position, the length of last word would be length
[  length-1   -   (last space index+1)  ] +1


Input:"a"
Output:-1
Expected:1



// NOTE: space may happend at the last character 
// STOP at the last character or last space
 int idx = s.length()-1; 
while ( idx >=0 && s.charAt(idx) == ' ') idx--;

 // NOTE: stop at the last two space
 int idx2 = idx; 
while ( idx2> =0 && s.charAt(idx) !=' ' ) idx2--;


'
// time:O(string length), Space:O(1)
public int lengthOfLastWord(String s)
{



       // validate the input
       if ( s == null || s.length() ==0 )
             return 0;




       //int spaceIndex = s.length(); 
       //for (int i = 0;i< s.length();i++)
       //{
       //       //if (s.charAt(i) == " ")
       //       // NOTE: is char
       //       if (s.charAt(i) == ' ')
       //           spaceIndex = i;
       //}
       // NOTE: space may happend at the last character
       // STOP at the last character or last space
       int idx = s.length()-1;  
       while ( idx >=0 && s.charAt(idx) == ' ')
           idx--;

        


       // NOTE: stop at the last two space
       int idx2 = idx;
       while ( idx2> =0 && s.charAt(idx) !=' ' )
            idx2--;



       //return (s.length - 1) - (spaceIndex +1) +1 
       //return s.length - spaceIndex -1;
       return idx - idx2;



}
3. Similar Ones

No comments:

Post a Comment