LengthOfLastWord
どこまで行っても私たちも、放課後のティータイム!
前言:
昨天的鱼刺被我掏下去啦!今天去面试了个同学,感觉和之前的同学比较的话,他准备得不错。注意面试过程中有不会的就说不会,不要强答,越答越错,说不会面试官就直接跳过,之后对你的整体感觉会好很多,感觉就是全都会的样子。当然,不要什么都不会,嘿嘿嘿。。。
package string;
import java.util.Arrays;
/**
* @author BlackSugar
* @date 2019/4/17
* Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
* <p>
* If the last word does not exist, return 0.
* <p>
* Note: A word is defined as a character sequence consists of non-space characters only.
* <p>
* Example:
* <p>
* Input: "Hello World"
* Output: 5
*/
public class LengthOfLastWord {
/**
* 获取字符串最后一个单词的长度
* 思想:lastIndexOf、split
*
* @param s
* @return
*/
public int lengthOfLastWord(String s) {
if (null == s || s.length() == 0) {
return 0;
}
s = s.trim();
int index = s.lastIndexOf(" "), length = s.length();
return length - 1 - index;
}
public static void main(String[] args) {
System.out.println(new LengthOfLastWord().lengthOfLastWord("a "));
}
}
总结:
这道题简单得令人发指,没什么好说的,如果必须要说难点就是不能使用内置方法,必须用charAt,这样就要遍历一次,没什么意义,就没写了 ? 代码github
1、时间O(1)
2、空间O(1)