标签:
Given a string s consists of upper/lower-case alphabets and empty space characters ‘ ‘
, return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
For example,
Given s = "Hello World"
,
return 5
.
这题还是比较容易的,用正则表达式感觉更简单一点,代码如下:
import java.util.regex.*; public class Solution { public int lengthOfLastWord(String s) { ArrayList<String> word_list = new ArrayList<String>(); Pattern p = Pattern.compile("\\w+");//匹配正则表达式 Matcher m = p.matcher(s); while(m.find()){ word_list.add(m.group()); } int size = word_list.size(); //size==0表示没有找到任何单词 if(size==0){ return 0; } return word_list.get(size-1).length(); } }
不用正则表达式代码:
public class Solution { public int lengthOfLastWord(String s) { if(s.length()==0){ return 0; } char[] array = s.toCharArray(); int size = array.length; ArrayList<String> list = new ArrayList<String>(); String word = "";//临时存储一个单词 int flag = 0;//flag==1时表示当前正在记录一个单词 for(int i=0;i<size;i++){ if(array[i]!=‘ ‘){ word = word+array[i]; flag = 1;//修改flag表示当前开始记录一个单词 } //如果遇到空格或者循环结束则将flag置0,表示当前单词记录结束 if(array[i]==‘ ‘||i==size-1){ flag = 0; } //如果word非空并且flag==0则表示一个单词记录完毕并将其存入list中,同时word置空 if(!word.isEmpty()&&flag==0){ list.add(word); word = ""; } } if(list.isEmpty()){ return 0; } return list.get(list.size()-1).length(); } }
标签:
原文地址:http://www.cnblogs.com/mrpod2g/p/4269710.html