为了更好地解释它,假设我得到两个字符串作为输入,然后比较它们是否匹配。但是,如果某些字母被重复,它仍然会被视为匹配
输入:" alexex ", "输出:真正的
输入:"saeed";输出:假
输入:" lelee", " lelee"输出:真正的
My c++ function
bool isLongPressedName(string name, string typed) {
if(name == typed) return true;
size_t lenName = name.length();
for(size_t i = 0; i < lenName; i){
//tried to check if typed contains all letters from name
}
//so if contains all letters inside even if its bigger and contains
//long pressed letter return true
return false
}`
这是一个受欢迎的网站之一的作业,所以我可以检查解决方案也在那里,但我希望这里有人可以帮助我更好地理解它。因为我有点被我的想法卡住了,并且开始认为它的方法是错误的。
对于初学者,函数参数的引用类型应该是const std::string &
或std::string_view
。
你所需要的只是成员函数find
。
函数isLongPressedName
可以如下面的示例程序中所示的方式查找。
#include <iostream>
#include <iomanip>
#include <string>
bool isLongPressedName( const std::string &name, const std::string &typed )
{
bool present = not ( typed.size() < name.size() );
for ( std::string::size_type i = 0, pos = 0; present && i < name.size(); i++ )
{
pos = typed.find( name[i], pos );
if ( ( present = pos != std::string::npos ) ) ++pos;
}
return present;
}
int main()
{
std::cout << std::boolalpha << isLongPressedName( "alex" , "aaleex" ) <<'n';
std::cout << std::boolalpha << isLongPressedName( "saeed" , "ssaaedd" ) << 'n';
std::cout << std::boolalpha << isLongPressedName( "leelee", "lleeelee" ) << 'n';
return 0;
}
程序输出为
true
false
true
或者如果字符串typed
不包含字符串name
中存在的字符以外的字符,则该函数可以按照以下方式执行
#include <iostream>
#include <iomanip>
#include <string>
bool isLongPressedName( const std::string &name, const std::string &typed )
{
bool present = not ( typed.size() < name.size() );
for ( std::string::size_type i = 0, pos = 0; present && i < name.size(); i++ )
{
if ( ( present = pos < typed.size() ) )
{
if ( i != 0 && name[i] != typed[pos] )
{
pos = typed.find_first_not_of( name[i - 1], pos );
}
if ( ( present = pos != std::string::npos && name[i] == typed[pos] ) )
{
++pos;
}
}
}
return present;
}
int main()
{
std::cout << std::boolalpha << isLongPressedName( "alex" , "aaleex" ) <<'n';
std::cout << std::boolalpha << isLongPressedName( "saeed" , "ssaaedd" ) << 'n';
std::cout << std::boolalpha << isLongPressedName( "leelee", "lleeelee" ) << 'n';
return 0;
}
同样,程序输出是
true
false
true
我认为在这里使用集合会是一个更好的方法
bool isLongPressedName(string name, string typed) {
set<char> s;
for(auto i : typed) {
s.insert(i);
}
typed = "";
for(auto j : s) {
typed += j;
}
return (name == typed);
}