Java solutions, one use splite, another without


  • 0
    G
    	public static int lengthOfLastWord(String s){
                    //use " " to divide the string
    		String []array=s.split(" ");
    		if(array.length==0){
    			return 0;
    		}
    		//return the length of last word
    		return array[array.length-1].length();
    	}

  • 0
    G
    	public static int lengthOfLastWord(String s){
    		int space=0;//count the space from the right end to the last word
    		boolean went=false;//mark whether counting space or not
                    if(s.length()!=0){
    			int i;
    			for(i=s.length()-1;i>=0;){
    				if(s.charAt(i)==' ' && went==false){//count space if not counting before
    					i--;
    					space++;
    				}else if(s.charAt(i)!=' '){
    					i--;
    					went=true;
    				}else if(s.charAt(i)==' ' && went==true){//if meet a space second time
    					break;
    				}
    			}
    			return s.length()-space-i-1;//return the last word length
    		}
    		return 0;
    	}

Log in to reply
 

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