算法练习题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");
        }
    }
}
相关推荐
默默coding的程序猿20 分钟前
3.前端和后端参数不一致,后端接不到数据的解决方案
java·前端·spring·ssm·springboot·idea·springcloud
虾球xz24 分钟前
CppCon 2018 学习:EFFECTIVE REPLACEMENT OF DYNAMIC POLYMORPHISM WITH std::variant
开发语言·c++·学习
在未来等你33 分钟前
JVM调优实战 Day 15:云原生环境下的JVM配置
java·jvm·性能优化·虚拟机·调优
NAGNIP34 分钟前
一文搞懂FlashAttention怎么提升速度的?
人工智能·算法
funnycoffee12334 分钟前
Huawei 6730 Switch software upgrade example版本升级
java·前端·华为
Java初学者小白35 分钟前
秋招Day15 - Redis - 缓存设计
java·数据库·redis·缓存
缘来是庄35 分钟前
设计模式之组合模式
java·设计模式·组合模式
DKPT37 分钟前
Java组合模式实现方式与测试方法
java·笔记·学习·设计模式·组合模式
G探险者1 小时前
《如何在 Spring 中实现 MQ 消息的自动重连:监听与发送双通道策略》
java·开发语言·rpc