算法练习题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");
        }
    }
}
相关推荐
雾月5510 分钟前
LeetCode 1292 元素和小于等于阈值的正方形的最大边长
java·数据结构·算法·leetcode·职场和发展
OpenC++39 分钟前
【C++QT】Buttons 按钮控件详解
c++·经验分享·qt·leetcode·microsoft
24k小善1 小时前
Flink TaskManager详解
java·大数据·flink·云计算
想不明白的过度思考者1 小时前
Java从入门到“放弃”(精通)之旅——JavaSE终篇(异常)
java·开发语言
YuforiaCode1 小时前
第十二届蓝桥杯 2021 C/C++组 直线
c语言·c++·蓝桥杯
.生产的驴2 小时前
SpringBoot 封装统一API返回格式对象 标准化开发 请求封装 统一格式处理
java·数据库·spring boot·后端·spring·eclipse·maven
猿周LV2 小时前
JMeter 安装及使用 [软件测试工具]
java·测试工具·jmeter·单元测试·压力测试
知来者逆2 小时前
计算机视觉——速度与精度的完美结合的实时目标检测算法RF-DETR详解
图像处理·人工智能·深度学习·算法·目标检测·计算机视觉·rf-detr
晨集2 小时前
Uni-App 多端电子合同开源项目介绍
java·spring boot·uni-app·电子合同
时间之城2 小时前
笔记:记一次使用EasyExcel重写convertToExcelData方法无法读取@ExcelDictFormat注解的问题(已解决)
java·spring boot·笔记·spring·excel