一、题目链接
http://noi.openjudge.cn/ch0107/24/
二、解题思路(Java)
◎ 将问题分解为三个子问题:
⑴ 获得指定单词序列中的有效单词集合 → 设计public String[] getValidWords(String text)方法完成;
⑵ 统计并返回指定单词序列中每个单词的长度 → 设计public int[] lengthOfEachWord(String text)方法完成;
⑶ 输出指定单词序列中每个单词的长度 → 设计public void printAnswer(String text)方法完成;
◎ public String[] getValidWords(String text)方法:
◇ 参数text为String类型的对象,存储指定单词序列;
△ 返回String类型的数组,存储text中的有效单词集合;
→ 首先,int n = text.length()代表text的长度,int m = 0存储text中的有效单词个数;
→ 其次,String[] ans = new String[n]存储text中的有效单词集合,String[] words = text.split(" ")通过一个空格将text分割
为若干单词集合;
→ 然后,利用foreach循环遍历words中的每个元素word:
*** 如果!word.isEmpty(),也即当前单词是有效单词,则
令ans[m] = word,也即将当前单词推入ans数组中;
令m++,也即有效单词的个数增加1个;
→ 上述foreach循环结束后,ans数组中[0,m-1]范围内的元素代表text中的m个有效单词,返回ans;
◎ public int[] lengthOfEachWord(String text)方法:
◇ 参数text为String类型的对象,存储指定单词序列;
△ 返回int类型的数组,存储text中每个单词的长度;
→ 首先,String[] words = getValidWords(text)获取text中的有效单词集合;
→ 其次,int n = words.length代表有效单词的个数,int[] ans = new int[n]存储text中每个单词的长度;
→ 然后,从第一个单词开始,到最后一个单词为止,利用循环i处理如下:
*** 令ans[i] = words[i].length(),依次存储每个单词的长度;
→ 上述循环结束i后,ans中存储了text中每个单词的长度,返回ans;
◎ public void printAnswer(String text)方法:
◇ 参数text为String类型的对象,存储指定单词序列;
→ 首先,int[] ans = lengthOfEachWord(text)存储text中每个单词的长度;
→ 其次,输出ans[0],也即第一个单词的长度;
→ 然后,从第二个单词开始,到最后一个单词为止,利用循环i处理如下:
*** 先输出一个逗号,再输出单词的长度ans[i];
◎ 在main方法中调用printAnswer方法,注入相应的参数后即可获得计算结果。
三、解题思路(C++)
四、Java程序
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public String[] getValidWords(String text) {
int n = text.length();
int m = 0;
String[] ans = new String[n];
String[] words = text.split(" ");
for (String word : words) {
if (!word.isEmpty()) {
ans[m] = word;
m++;
}
}
return Arrays.copyOfRange(ans, 0, m);
}
public int[] lengthOfEachWord(String text) {
String[] words = getValidWords(text);
int n = words.length;
int[] ans = new int[n];
for (int i = 0; i < n; i++) {
ans[i] = words[i].length();
}
return ans;
}
public void printAnswer(String text) {
int[] ans = lengthOfEachWord(text);
System.out.print(ans[0]);
for (int i = 1; i < ans.length; i++) {
System.out.print("," + ans[i]);
}
}
public static void main(String[] args) {
Main test = new Main();
Scanner input = new Scanner(System.in);
String text = input.nextLine();
test.printAnswer(text);
}
}
五、C++程序