two pointer method in java


  • 0
    L

    The main idea is using two pointer to walk each segment and count

    1. pointer starts from the non-whitespace char;
    2. walker starts from the pointer, once reaches the whitespace char it stops. and then count increases by 1.
    3. reset the pointer to walker, recursion.

    public class Solution {
    public int countSegments(String s) {
    int count=0;
    int pointer=0; /*poiting to the first char is not ' ' */
    int walker=0; /*starting from pointer, once reach'', count++ */

       for(pointer=0;pointer<s.length();pointer++){
        if(s.charAt(pointer)!=' '){
            for(walker=pointer;walker<s.length();walker++){
                if(s.charAt(walker)==' ')
                    break;
                }
            count++;
            pointer=walker;
        }
       }
       return count;
    }
    

    }


Log in to reply
 

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