【问题标题】:First capital function using O(log n)使用 O(log n) 的第一个大写函数
【发布时间】:2023-03-21 17:55:01
【问题描述】:

我编写了以下代码来查找字符串中的第一个大写字母:

char first(const char str[], int n)
{
    for (int i = 0; i < n; i++)
        if (isupper(str[i]))
            return str[i];
    return 0;
}

代码有效,但我需要使用 O(log n) 操作来修改它,我相信这是二进制搜索。我怎么能修改代码来遵循呢?任何提示/建议都会有所帮助。 (const char str[] 为字符串,int n 为字符串长度)。

编辑:所有小写字母出现在大写字母之前

【问题讨论】:

  • 这可能吗?如果您对输入字符串一无所知,最坏的情况永远是您必须检查每个字母对吗?
  • 如果输入是任意字符串,不可能比 O(n) 最坏情况做得更好。关于输入的其他信息是否已知?
  • 你不能这样做,除非输入的字符串是排序好的...
  • ... 并且对输入字符串进行排序需要 O(n*log n) 除非您使用 O(n) Quantum Bogo Sort ;-)
  • @Jason 到目前为止你有什么尝试?这只是一个二分搜索,当你找到一个小写字母时,你看“右”,每当你遇到大写字母时,你看“左”,直到你找到第一个小写字母存在于紧靠左侧的情况大写字母。

标签: c


【解决方案1】:

由于“所有”小写字母出现在大写字母之前,我们可以使用二进制搜索来查找大写字母。现在,如果我们找到一个大写字母,那么我们将只检查相邻的左侧字符。如果它是大写,那么显然第一个大写字符位于当前找到的大写字符的左侧。如果不是,那么我们找到了第一个大写字符。 否则,我们将继续搜索字符串的右侧。

二分搜索实现是:

char first(const char str[], int n){
        int low = 0;
        int high = n-1;
        while(low<=high){
            mid=(low+high)/2;
            if(isupper(str[mid]){
                if(mid >0){ //we can't access negative index
                    if(!isupper(str[mid-1]){ //if adjacent left char is not capital, then this is first Capital char
                        return str[mid];
                    }else {
                        high=mid-1; //as this is not first Capital char, search left
                    }
                else{
                    return str[mid]; //as mid is first char of string and capital as well
                }
            }
            else {
                low=mid+1;
            }
        }
    return 0;
    }

【讨论】:

    猜你喜欢
    • 2011-11-23
    • 1970-01-01
    • 2011-12-12
    • 2015-08-28
    • 1970-01-01
    • 2013-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多