Java AC in-place pure two pointer, no trim()


  • 0

    For this kind of problem in an interview , usually input is given as a char[] and you have to do it in-place without manipulate the input, such as using trim(). You should only use indices to complete the job.

    
    public class Solution {
        public int lengthOfLastWord(String s) {
            char[] words = s.toCharArray();
            int i = words.length - 1;
            while (i >= 0 && words[i] == ' ') {
                i--;
            }
            int j = i;
            while (j >= 0 && words[j] != ' ') {
                j--;
            }
            return i - j;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.