class Solution {
public:
string longestCommonPrefix(vector<string>& vct) {
int z = vct[0].size() -1 ;
int len = vct.size();
int count = 0;
salto:
for (int i=0 ; i<len && z > 0 ; i++) cout << vct[i]<< " " << z<< endl;
for (int i=0 ; i<len-1 ; i++){
if (vct[i] != vct[i+1])
for (int i=0 ; i<len ; i++) {
vct[i] = vct[i].substr(0,z);
}
z-=1;
goto salto;
}
}
我正在尝试在leetcode上用c++做一个问题,其中包括找到一系列字符串的共同首字母,我的算法的想法是通过比较每个元素的for循环来检查字符串是否相等与下一个向量的起始向量,那么如果它们不同,则消除最后一个字母,而如果它们相等,则返回剩余的字符串,这应该是公共部分,问题是通过执行代码,程序停止截断字符串之后第二,例如,输入向量“花,流,飞行”,输出是
flower
flow
flight
flower
flow
flight
flowe
flow
fligh
flow
flow
flig
flow
flow
flig
flow
flow
flig
依此类推到无穷大,它在流动时停止,奇怪的是,如果我这样做<< vct[i].substr(0,z) << vct[i] << endl I get that v1 and v1substr have different values even though I did vct = vct.substr() right before, in particular vct[i].substr(0,z) printed has the value that I would expect vct to have but instead it is not modified. also if I do vct = vct.substr(0,1) I can modify vct beyond the "flow" however this does not happen using the variable z. Can someone help me?
我尝试将 leetcode 给我的向量元素移动到我创建的另一个变量中,但得到了相同的结果。此外,即使在代码开头修改向量内的字符串,即使编译器没有给出错误,通过尝试使用 for 循环的变量修改它们也会阻止向量内字符串的所有修改
使用您的代码:
使用 goto 创建复杂的控制流程,很容易导致
如果不小心处理,会出现无限循环。循环结构缺少
明确的退出条件。
使用 vct[i] = vct[i].substr(0,z) 修改向量元素
直接不影响后续正确比较
因为原始字符串在循环上下文之外保持不变。
修改:
删除 goto:重构后的代码使用简单的 while 循环来 管理控制流,更易于阅读和维护。
while 循环检查当前字符串是否以前缀开头。如果 不,前缀一次缩短一个字符,直到匹配 找到或者前缀为空。
for (int i = 1; i < vct.size(); i++) { // While the current string does not start with the prefix while (vct[i].find(prefix) != 0) { // Reduce the prefix by one character prefix = prefix.substr(0, prefix.size() - 1); // If the prefix is empty, there is no common prefix if (prefix.empty()) return ""; } } return prefix;