算法练习题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");
        }
    }
}
相关推荐
做怪小疯子几秒前
LeetCode 热题 100——哈希——最长连续序列
算法·leetcode·哈希算法
Lxinccode10 分钟前
docker(25) : 银河麒麟 V10离线安装docker
java·docker·eureka·银河麒麟安装docker·银河麒麟安装compose
遇见火星10 分钟前
LINUX的 jq命令行处理json字段指南
java·linux·json·jq
Dream it possible!20 分钟前
LeetCode 面试经典 150_二叉树_二叉树展开为链表(74_114_C++_中等)
c++·leetcode·链表·面试·二叉树
做怪小疯子25 分钟前
LeetCode 热题 100——双指针——三数之和
算法·leetcode·职场和发展
高山上有一只小老虎33 分钟前
等差数列前n项的和
java·算法
rockmelodies37 分钟前
东方通安装
java
sin_hielo41 分钟前
leetcode 2536
数据结构·算法·leetcode
flashlight_hi1 小时前
LeetCode 分类刷题:203. 移除链表元素
算法·leetcode·链表
py有趣1 小时前
LeetCode算法学习之数组中的第K个最大元素
学习·算法·leetcode