解题思路
- 这道题要求计算字符串最后一个单词的长度,可以从字符串末尾开始向前遍历
- 从后向前找到第一个空格,即可得到最后一个单词
- 如果没有找到空格,说明整个字符串就是一个单词
- 最后一个单词的长度就是从字符串末尾到最后一个空格之间的字符数
代码
#include <iostream>
#include <string>
int main() {
std::string s;
int ans = -1;
while (std::cin >> s) {
ans = s.length();
}
std::cout << ans << std::endl;
return 0;
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int count = 0;
for(int i = str.length() - 1; i >= 0; i--) {
if(str.charAt(i) == ' ') break;
count++;
}
System.out.println(count);
}
}
s = input()
print(len(s.split()[-1]))
算法及复杂度
- 算法:从后向前遍历字符串,统计最后一个单词的长度。也可以不断地输入一个字符串,统计字符串的长度。Python解法利用
split()
方法直接分割字符串。 - 时间复杂度:
,其中n为字符串长度。
- 空间复杂度:
,只需要常数级额外空间。