C语言字符串中的最长递增子序列

发布时间:2024-08-30 14:27:39 作者:小樊
来源:亿速云 阅读:79

在C语言中,要找到一个字符串中的最长递增子序列,可以使用动态规划算法

#include<stdio.h>
#include<string.h>

int longestIncreasingSubsequence(const char *str) {
    int n = strlen(str);
    int dp[n];

    for (int i = 0; i < n; i++) {
        dp[i] = 1;
    }

    int maxLength = 1;

    for (int i = 1; i < n; i++) {
        for (int j = 0; j < i; j++) {
            if (str[i] > str[j]) {
                dp[i] = dp[i] > dp[j] + 1 ? dp[i] : dp[j] + 1;
            }
        }
        maxLength = maxLength > dp[i] ? maxLength : dp[i];
    }

    return maxLength;
}

int main() {
    const char *str = "ABCAGH";
    printf("The length of the longest increasing subsequence in \"%s\" is: %d\n", str, longestIncreasingSubsequence(str));
    return 0;
}

这个程序首先计算字符串的长度,然后创建一个动态规划数组dp,用于存储每个位置的最长递增子序列长度。接下来,程序遍历字符串中的每个字符,并更新dp数组。最后,程序返回dp数组中的最大值,即最长递增子序列的长度。

在这个例子中,输入字符串为"ABCAGH",输出结果为:The length of the longest increasing subsequence in “ABCAGH” is: 4。最长递增子序列是"ABCG"。

推荐阅读:
  1. C语言的回调函数怎么使用
  2. C语言中函数参数的入栈顺序

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c语言

上一篇:C语言字符串中的最长回文子串

下一篇:C语言字符串中的最短超串问题

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》