Compound Words UVA - 10391(c++用法中substr函数用法+map实现)
題意:
給出字典中一堆單詞,單詞的輸入方式是以字典序輸入的。問:在這一堆單詞中,有那些單詞是通過其它兩個(gè)單詞組合而來的。按字典序升序輸出這些單詞。
題目:
You are to find all the two-word compound words in a dictionary. A two-word compound word is a
word in the dictionary that is the concatenation of exactly two other words in the dictionary.
Input
Standard input consists of a number of lowercase words, one per line, in alphabetical order. There will
be no more than 120,000 words.
Output
Your output should contain all the compound words, one per line, in alphabetical order.
Sample Input
a
alien
born
less
lien
never
nevertheless
new
newborn
the
zebra
Sample Output
alien
newborn
分析:
如果用兩個(gè)字符串拼接看拼接好的字符串是否在字典中,一定會(huì)超時(shí)。
我們可以逆向,由于字符串的長(zhǎng)度不是很長(zhǎng),所以把一個(gè)字符串拆為兩個(gè)字符串看這兩個(gè)字符串是否都在字典中即可
在這里我用的map實(shí)現(xiàn)+substr函數(shù)
c++用法中substr函數(shù)用法
#include<string> #include<iostream> using namespace std; int main() { string s("12345asdf"); string a = s.substr(0,5); //獲得字符串s中從第0位開始的長(zhǎng)度為5的字符串 string b=s.substr(5);/**==string b=s.substr(5,9)*////先有pos,若無n,直接認(rèn)為是字符串長(zhǎng)度 cout << a << endl; cout << b << endl; }ac代碼
#include<iostream> #include<string.h> #include<map> #include<string> #include<algorithm> using namespace std; const int M=1e6+10; map<string,int>mp;//使用map對(duì)于字典中的單詞進(jìn)行映射,作用就是用于查詢單詞是否字典中 string s[M]; int k; int main() {k=0;while(cin>>s[k]){mp[s[k]]=1;k++;}for(int i=0; i<k; i++)for(int j=0; j<s[i].length(); j++){string u,v;u=s[i].substr(0,j);//然后從第一個(gè)開始,將每個(gè)單詞分成它所能變成的任意兩個(gè)單詞v=s[i].substr(j);///substr是C++語言函數(shù),主要功能是復(fù)制子字符串,要求從指定位置開始,并具有指定的長(zhǎng)度。if(mp[u]&&mp[v])//如果分成的兩個(gè)單詞的映射值均為1,那么這個(gè)就輸出這個(gè)單詞{cout<<s[i]<<endl;break;}}return 0; } 創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的Compound Words UVA - 10391(c++用法中substr函数用法+map实现)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 枇杷蜜的功效与作用、禁忌和食用方法
- 下一篇: 红苋菜的功效与作用、禁忌和食用方法