一、练习
字符串遍历 | 边界问题 | ''是字符 |
1.if判断
using namespace std;
#include<iostream>
#include<string>
int solve(string s){
//..
int sum=0,item=0;
for (auto ch : s){
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u'){
item++;
if(sum<item) sum=item;
}
else item=0;
}
return sum;
}
2.switch判断
#include<string>
#include<cstring>
#include<string>
int solve(string s){
//..
int sum=0,item=0;
for (auto ch : s){
switch(ch){
case 'a':
item+=1;
cout<<ch<<item;
if(sum<item)
{sum=item;}
break;
case 'e':
item+=1;
cout<<ch<<item;
if(sum<item)
{sum=item;}
break;
case 'i':
item+=1;
cout<<ch<<item;
if(sum<item)
{sum=item;}
break;
case 'o':
item+=1;
cout<<ch<<item;
if(sum<item)
{sum=item;}
break;
case 'u':
item+=1;
cout<<ch<<item;
if(sum<item)
{sum=item;}
break;
default:
if(sum<item)
{sum=item;}
cout<<item<<endl;
item=0;
}
}
cout<<sum;
return sum;
}
二、拓展
从Solutions模块学来的
1. s.length()在C++中用于获取字符串的长度,s.length()
方法返回一个无符号整数
using namespace std;
int solve(string s){
int count = 0;
int best = 0;
for(int i=0;i<s.length();i++)
{
if(s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u') count++;
else count = 0;
best = max(best, count);
}
return best;
}
2. const char& s
std::unordered_set
vowels.count(s)
使用引用( |
std::unordered_set 其和std::set 不同的一点是,前者是没有顺序的,而后者会对元素顺序进行排序,也正是因为其没有顺序,无序set的速度要快得多 |
std::unordered_set<char>.count 是一个 C++ STL 函数,用于检查 unordered_set<char> 中是否存在特定的元素。该函数返回一个整数,表示特定键值的出现次数。 |
#include <string>
#include <unordered_set>
using namespace std;
int solve(string word){
std::unordered_set<char> vowels {'a', 'e' ,'i', 'o' , 'u'};
int longest = 0, longSub = 0;
for (const char& s : word) {
longSub = (vowels.count(s)) ? (longSub + 1) : 0;
if (longSub > longest)
longest = longSub;
}
return longest;
}
3.C++中std::string::npos
(1)它是一个常量静态成员值,对于 size_t 类型的元素具有最高可能值。 |
(2)它实际上意味着直到字符串的末尾。 |
(3)它用作字符串成员函数中长度参数的值。 |
(4)作为返回值,它通常用于表示没有匹配项。 |
(5)数据类型为size_t的话string:npos常量被定义为-1,因为size_t是无符号整数类型,-1是该类型的最大可能表示值。 |
int solve( std::string s ) {
int l{}, t{};
const std::string v{ "aeiou" };
for ( const char c : s )
if ( v.find( c ) != v.npos ) ++t;
else l = std::max( l, t ), t = 0;
return std::max( l, t );
}