算法练习题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");
        }
    }
}
相关推荐
挨代码2 小时前
UE_C++ —— Gameplay Modules
c++·ue
脑洞专家3 小时前
角点检测算法各自优缺点
人工智能·算法·计算机视觉
爆爆凯3 小时前
MobaXterm_Portable_v23.2 免费下载与使用教程(附安卓替代方案)
java·github
C#Thread4 小时前
机器视觉--Halcon的数据结构(数组)
算法
+7204 小时前
如何在java中用httpclient实现rpc get请求
java·qt·rpc
秋野酱4 小时前
基于 JavaWeb 的 SSM+Maven 微信小程序快递柜管理系统设计和实现(源码+文档+部署讲解)
java·微信小程序·maven·课程设计
你在我身后4 小时前
Spring-JAVA
java·后端·spring
卓越软件开发5 小时前
Java计算机毕业设计基于SSM宠物美容信息管理系统数据库源代码+LW文档+开题报告+答辩稿+部署教程+代码讲解
java·课程设计·宠物
垠二5 小时前
L2-4 寻宝图
数据结构·算法