返回
算法练习第17道:最后一个单词的长度
前端
2024-01-31 19:33:38
引言
编程练习是磨练算法和数据结构技能的绝佳方式。其中一道经典练习题就是「最后一个单词的长度」,它考验了我们对字符串操作的基本理解。
算法概述
解决「最后一个单词的长度」问题的算法很简单:
- 从字符串的末尾开始遍历。
- 忽略所有尾随空格。
- 当遇到第一个非空格字符时,开始计数单词长度。
- 继续计数,直到再次遇到空格或字符串的开头。
- 返回计数的单词长度。
示例代码
public class LastWordLength {
public static int lengthOfLastWord(String s) {
// 从末尾开始遍历
int index = s.length() - 1;
// 忽略尾随空格
while (index >= 0 && s.charAt(index) == ' ') {
index--;
}
// 开始计数单词长度
int count = 0;
while (index >= 0 && s.charAt(index) != ' ') {
count++;
index--;
}
return count;
}
public static void main(String[] args) {
String s = "Hello World";
int result = lengthOfLastWord(s);
System.out.println("最后一个单词的长度:" + result);
}
}
优化
为了优化算法,我们可以使用正则表达式来更简洁地查找单词长度:
public class LastWordLength {
public static int lengthOfLastWord(String s) {
return s.trim().length() - s.trim().lastIndexOf(' ') - 1;
}
public static void main(String[] args) {
String s = "Hello World";
int result = lengthOfLastWord(s);
System.out.println("最后一个单词的长度:" + result);
}
}
总结
「最后一个单词的长度」是一个基本但有用的算法练习题,可以帮助我们理解字符串操作。通过使用正确的算法和优化技巧,我们可以有效解决此类问题,提升我们的编程能力。