算法练习题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");
        }
    }
}
相关推荐
掘金-我是哪吒6 分钟前
分布式微服务系统架构第157集:JavaPlus技术文档平台日更-Java多线程编程技巧
java·分布式·微服务·云原生·架构
飞翔的佩奇14 分钟前
Java项目:基于SSM框架实现的忘忧小区物业管理系统【ssm+B/S架构+源码+数据库+毕业论文+开题报告】
java·数据库·mysql·vue·毕业设计·ssm框架·小区物业管理系统
RainbowSea32 分钟前
跨域问题(Allow CORS)解决(3 种方法)
java·spring boot·后端
掘金-我是哪吒33 分钟前
分布式微服务系统架构第155集:JavaPlus技术文档平台日更-Java线程池实现原理
java·分布式·微服务·云原生·架构
RainbowSea36 分钟前
问题 1:MyBatis-plus-3.5.9 的分页功能修复
java·spring boot·mybatis
前端 贾公子39 分钟前
monorepo + Turborepo --- 开发应用程序
java·前端·javascript
三维重建-光栅投影1 小时前
VS中将cuda项目编译为DLL并调用
算法
不学会Ⅳ1 小时前
Mac M芯片搭建jdk源码环境(jdk24)
java·开发语言·macos
2401_881244401 小时前
牛客周赛99
c++
虫小宝1 小时前
高佣金返利平台监控体系建设:APM、链路追踪与佣金异常预警系统技术实现
java