算法练习题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");
        }
    }
}
相关推荐
splage19 小时前
Java进阶之泛型
java·开发语言
Meepo_haha19 小时前
python爬虫——爬取全年天气数据并做可视化分析
java
xiaohe0719 小时前
JAVA系统中Spring Boot 应用程序的配置文件:application.yml
java·开发语言·spring boot
羊小蜜.19 小时前
C++17: map & multimap—— 键值映射容器
开发语言·c++·stl
Eternity_GQM19 小时前
【CMake入门】
java·开发语言
糖猫猫cc19 小时前
Kite 实现逻辑删除
java·kotlin·orm·kite
Memory_荒年19 小时前
Dubbo调优实战:从QPS 1000到10000的惊险过山车之旅
java·后端·dubbo
Cosolar19 小时前
别再羡慕 Python 了!Java 开发者的 AI Agent 全指南:四大框架从选型到实战
java·人工智能·后端
tankeven19 小时前
HJ156 走迷宫
c++·算法
色空大师19 小时前
网站搭建实操(三)后台管理-2-forum-core)
java·redis·网站·搭建网站