public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String findVal = scanner.nextLine().toLowerCase();
String word = scanner.nextLine().toLowerCase();
String[] str = word.split(" ");
int count = 0,firstIndex = -1;
for(int i = 0;i < str.length;i++){
if(str[i].equals(findVal)){
if(count == 0){
firstIndex = i;
}
count++;
}
}
if(count == 0){
System.out.println(-1);
}else {
System.out.println(count + " " + firstIndex);
}
scanner.close();
}
洛谷P1308 只有30分求解
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
3条回答 默认 最新
a5156520 2023-04-26 16:45关注应该是因为,判断文章字符串第一次出现给定单词的判断那里需要改进下,通过参考洛谷题解,发现判断此单词第一次出现的位置,还需要满足另一个条件,即是在文章字符串第一次出现的前面需要是空格或是文章字符串开头,以及此位置一个给定单词长度后是空格或是达到文章字符串结尾才可以。
修改如下:
参考链接:https://blog.csdn.net/qq_45771848/article/details/116517753https://www.luogu.com.cn/problem/P1308https://blog.csdn.net/u010227042/article/details/119032461https://www.luogu.com.cn/problem/solution/P1308?page=4https://blog.csdn.net/m0_53370922/article/details/127464290import java.util.Scanner; // https://blog.csdn.net/qq_45771848/article/details/116517753 public class Main洛谷P1308_寻找字符串中单词出现的次数_2023_4_26 { // https://www.luogu.com.cn/problem/P1308 public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String findVal = scanner.nextLine().toLowerCase(); String word = scanner.nextLine().toLowerCase(); String[] str = word.split(" "); int count = 0,firstIndex = -1; for(int i = 0;i < str.length;i++){ //System.out.print(str[i]+" "); if(str[i].equals(findVal)){ // if(count == 0){ // firstIndex = i; // } count++; } } //System.out.println(); // https://blog.csdn.net/u010227042/article/details/119032461 // luogu.com.cn/problem/solution/P1308?page=4 int index=0; // 从文章字符串下标为0的字符开始判断 int flen = findVal.length();// 给定单词的长度 int wlen = word.length(); // 文章的长度 // https://blog.csdn.net/m0_53370922/article/details/127464290 while(index<word.length()) { // 在文章字符串 下标为index的位置开始寻给定单词 firstIndex = word.indexOf(findVal,index); if(firstIndex!=-1) { // 如果找到给定单词 // 并且在此位置的前一个字符为空格,或或者是文章字符串成开头, //并且 此位置一个给定单词长度后是一个空格,或者达到了文章字符串结尾, //则判定此位置为第一次出现给定单词的位置,break退出循环 if((firstIndex==0||word.charAt(firstIndex-1)==' ') &&((firstIndex+flen==wlen)||word.charAt(firstIndex+flen)==' ')) { break; } // 如果不满足,上述条件,则继续寻找,位置为当前寻找的位置+给定单词的长度 index = firstIndex+flen; continue; }else { // 如果没找到,则退出循环 break; } } if(count == 0){ System.out.print(-1); }else { System.out.print(count + " " + firstIndex); } scanner.close(); } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报 编辑记录