首页 > 解决方案 > 计算双引号内的字符数

问题描述

我想查找双引号内的字符数。

例如 :

情况1

“你好世界”,“一些

输出:错误 // Some 后缺少引号

案例2

“你好词”,“一些”

output : 14 // 所有引号都完整

我编写了使用递归计算总字符数、第一个引号索引和引号总数的程序。

我应该使用什么方法来解决这个问题?

标签: c++algorithmrecursion

解决方案


请帮助我弄清楚我应该使用什么方法来解决上述问题。

您可以使用这种在线性时间内运行的更简单的方法,而不是使用递归:

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的评论。


推荐阅读