本文主要是介绍算法练习题11:单词出现次数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
c++解法
#include <bits/stdc++.h>
using namespace std;
int main() {string s1;string s2;getline(cin,s1);getline(cin,s2);for(int i = 0;i<s1.length();i++){s1[i] = tolower(s1[i]);}for(int i = 0;i<s2.length();i++){s2[i] = tolower(s2[i]);}s1 = " "+s1+" ";s2 = " "+s2+" ";if(s2.find(s1)==-1){cout<<"-1"<<endl;}else{int first = s2.find(s1);int count = 0;int index = s2.find(s1);while(index!=-1){count++;index = s2.find(s1,index+1);}cout<<count<<" "<<first<<endl;}return 0;}
java解法
import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);// 读取输入String targetWord = scanner.nextLine(); // 待查找的单词String text = scanner.nextLine(); // 文章内容// 初始化变量int count = 0;int firstPosition = -1;// 分割文章为单词数组并保留原始位置String[] words = text.split("\\s+");// 查找单词int position = 0; // 当前位置计数器for (String word : words) {// 使用正则表达式判断是否是完整的单词匹配if (word.equals(targetWord)) {count++;if (firstPosition == -1) {firstPosition = text.indexOf(word, position);}}// 更新位置计数器(加上当前单词长度和一个空格)position += word.length() + 1;}// 输出结果if (count > 0) {System.out.println(count + " " + firstPosition);} else {System.out.println("-1");}}
}
这篇关于算法练习题11:单词出现次数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!