c++ - 计算双引号内的字符数
问题描述
我想查找双引号内的字符数。
例如 :
情况1
“你好世界”,“一些
输出:错误 // Some 后缺少引号
案例2
“你好词”,“一些”
output : 14 // 所有引号都完整
我编写了使用递归计算总字符数、第一个引号索引和引号总数的程序。
我应该使用什么方法来解决这个问题?
解决方案
请帮助我弄清楚我应该使用什么方法来解决上述问题。
您可以使用这种在线性时间内运行的更简单的方法,而不是使用递归:
void countCharsWithinDoubleQuotes(const std::string& input)
{
size_t ans = 0;
bool quoteStarted = false;
// Iterate through the string and get the required counts
for (const auto& ch : input)
{
// Toggle the quote switch
if (ch == '"')
quoteStarted = !quoteStarted;
// Keep counting the characters after a starting double quote
else if (quoteStarted)
++ans;
}
// If a closing quote was not found, it was not balanced
if (quoteStarted) // quoteDidNotEnd
{
std::cout << "Error";
}
// Print the number of characters within all the double quotes
else
{
std::cout << ans;
}
}
编辑:
如果您需要更好的解释,请参阅问题下方JohnFilleau的评论。
推荐阅读
- python - 计算大型稀疏矩阵中所有列之间的皮尔逊系数的最快方法是什么?
- flutter - 如何检测小部件外部的点击?
- assembly - 完整的 32x32 => 64 位乘法结果的两半是什么?
- python - 无法检查 QAction
- r - R - For 循环针对数据框列表运行代码
- javascript - 使用 Mapbox GL JS 单击关闭标记层时如何关闭弹出窗口
- python - 显示奇怪行为的 RandomForestClassifier 的随机超参数搜索
- javascript - Javascript var 返回“未定义”
- php - 如何使用 php 从文本文件中显示定义列表
- javascript - 如何从重组转换为钩子?