4 条题解
-
3
坑:空格数量不一定是一个且可能出现在文章开头,所以你不能一个个单词读入(也许有办法计算空格数量?)
同时感觉缺一个把唯一的 hit 放最后的数据点
感觉开一个 的 char 数组很不优雅,所以这里我用的是 string
.substr(起始位置,长度) 返回子串,字符串可以直接使用 == 来进行比较
如果你和我一样打算给比较前的原始字符串前后加空格来避免给定单词是文章中单词的一部分时匹配上,注意考虑文章开头的情况。如果你给文章前也加一个空格的话,记得处理好 index 与原始字符串的偏移。
#include<bits/stdc++.h> using namespace std; int main(){ string word,art; int w=0,c=0,p=-1;//c for appear times count, p for first appear pos bool flag=false; // cin>>word; getline(cin,word); getline(cin,art); // cout<<art<<endl; for(int i=0;i<word.length();i++) if(word[i]>='A'&&word[i]<='Z') word[i]+=32; word+=' '; art+=' '; for(int i=0;i<art.length();i++) if(art[i]>='A'&&art[i]<='Z') art[i]+=32; for(int i=0;i<art.length()-word.length()+1;i++){ string tmp=art.substr(i,word.length()); // for(int j=0;j<tmp.length();j++) if(tmp[j]>='A'&&tmp[j]<='Z') tmp[j]+=32; if(word==tmp&&(i==0||art[i-1]==' ')){ ++c; if(!flag) p=i,flag=true; } } if(flag) cout<<c<<' '<<p; else cout<<-1; // cin>>word>>cmp; // for(int i=0;i<word.length();i++) if(word[i]>='A'&&word[i]<='Z') word[i]+=32; // bool flag=false; // do{ // for(int i=0;i<cmp.length();i++) if(cmp[i]>='A'&&cmp[i]<='Z') cmp[i]+=32; // if(word==cmp){ // if(!flag) p=w,flag=true; // ++c; // } // w+=cmp.length(); // // cout<<"[Debug]"<<w<<endl; // }while(cin>>cmp); // if(!flag) cout<<-1,exit(0); // else cout<<c<<' '<<p; return 0; }
-
0
need_f = input().strip().lower() txt = input().lower() word = txt.split() count = 0 first = 0 if need_f not in word: print(-1) else: for w in word: if need_f == w: count += 1 # 现在来查找单词第一次出现的位置 for i in range(len(txt)): # 三个判断是防止出现need_f包含在某个单词中, # 例如样例2,Ottoman包含了to,但是因为要查找第一次出现位置,而且空格也算一个字母位置,所以不能直接用列表或者find first = i if need_f == txt[i:i+len(need_f)]: # 首先要查找到字符 # 单词出现在文章最前,那么单词的后面应该有分隔符’ ‘ if i == 0 and txt[i+len(need_f)] == ' ': first = i break # 单词出现在文章最后,那么单词的前面应该有分隔符’ ‘ elif i == len(txt) and txt[i-1] == ' ': first = i break # 单词出现在文章中间,那么单词的左右应该有分隔符’ ‘ elif txt[i+len(need_f)] == ' ' and txt[i-1] == ' ': first = i break print(count,first)
-
0
python版 考虑前后空格问题
word = input().lower() sentencestr = input().lower() sentence = sentencestr.split() cnt = 0 sentencestr = " " + sentencestr sentencestr = sentencestr.replace(" "+word+" ","#"*(len(word)+2)) pos = sentencestr.find("#"*(len(word)+2)) if pos != -1: for idx,w in enumerate(sentence): if word == w: cnt += 1 print(cnt,end=" ") print(pos)
-
0
#主要考虑前后空格问题
str_1 = input().strip().lower() str_2 = input().lower() list_1 = str_2.split() # 先统计次数 count_1 = 0 for i in list_1: if i == str_1: count_1+=1 if count_1 == 0: print(-1) else: # 如果是第一个,那就右边加空格进行分割 if str_1 == list_1[0]: len_1 = len(str_2.split(str_1+" ")[0]) print(count_1,len_1) # 如果不是第一个,那就两边都加空格进行分割 else: len_1 = len(str_2.split(" "+ str_1+" ")[0]) print(count_1,len_1+1)
- 1
信息
- ID
- 309
- 时间
- 1000ms
- 内存
- 125MiB
- 难度
- 2
- 标签
- 递交数
- 231
- 已通过
- 73
- 上传者