gpt4 book ai didi

c++ - 不按特定顺序跳过多个循环(C++)

转载 作者:行者123 更新时间:2023-12-02 09:50:23 30 4
gpt4 key购买 nike

我正在尝试运行一个比较两个字符串并计算第一个字符串中第二个字符串中有多少个连续字母的代码。

编辑:该函数应如何工作的示例:

longest_letter_run(“this_is_some_text”,“ais_”)
应该返回7,因为最长的字母运行是“is_is_s”
因为文本的第一行没有“a”,所以不考虑a。

我的问题是,在运行并确认以下代码行正确之后,
(1)

if (word[i] == match[j]){

我想跳回到(2)中的下一个迭代
for (int i=0; i < word.size(); i++){

并继续这样做,直到(1)中的条件再次为假,然后在那之后我退出所有循环。

但是我不确定该怎么做。一些帖子建议使用标志或使用goto,但在这种情况下我认为不起作用。

这是我到目前为止的内容,它仅计算两个字符串中的字母出现次数(尚未计算连续的字母)
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;




int longest_letter_run(string word, string match){
int iter = 0;
for (int i=0; i < word.size(); i++){
for (int j=0; j <match.size(); j++){
if (word[i] == match[j]){
if (true){
++iter;
}

}

}

}

}

最佳答案

首先,请注意。 if (true)没有意义,可以删除。

要回答您的问题,如果我理解正确,则可以使用控制变量。 (正如其他人所说的,您可以只使用break代替控件)例如:

for (int i=0; i < word.size(); i++){
bool matched = false;
for (int j=0; j < match.size() && !matched; j++){
if (word[i] == match[j]){
matched = true;
++iter;
}
}
}

我认为这更符合您的需求:
#include <iostream>
#include <algorithm>


int longest_letter_run( const std::string &word, const std::string &match ) {
int max = 0;
for ( int i = 0; i < word.size(); i++ ) {
int count = 0;
int word_idx = i;
for ( int j = 0; j < match.size() && word_idx < word.size(); ++j, ++word_idx, ++count ) {
if ( word[word_idx] != match[j] ) {
break;
}
}
max = std::max( max, count );
}
return max;
}

int main() {
std::cout << longest_letter_run( "apples", "pp" ) << '\n';
std::cout << longest_letter_run( "appples", "p" ) << '\n';
std::cout << longest_letter_run( "weird", "weirdness" ) << '\n';
std::cout << longest_letter_run( "weirdweirdne", "weirdness" ) << '\n';
std::cout << longest_letter_run( "weirdweirdweirdnessweirdne", "weirdness" ) << '\n';

getchar();
}

随着输出
2
1
5
7
9

编辑:

好的,根据您的评论:

The only condition is that they need to be consecutive letters in "word" whose letters are also in "match". ordering on letters in "match" is unnecessary.


int longest_letter_run( const std::string &word, const std::string &match ) {
int max = 0;
int count = 0;
for ( int i = 0; i < word.size(); i++ ) {
if ( match.find( word[i] ) != std::string::npos )
++count;
else {
max = std::max( max, count );
count = 0;
}
}
max = std::max( max, count );
return max;
}

其输出为(具有与之前相同的主输出):
2
3
5
12
26

关于c++ - 不按特定顺序跳过多个循环(C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60152016/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com