[UVa OJ] Longest Common Subsequence
This is the classic LCS problem. Since it only requires you to print the maximum length, the code can be optimized to use only O(m) space (see here).
My accepted code is as follows.
1 #include <iostream> 2 #include <string> 3 #include <vector> 4 5 using namespace std; 6 7 int lcs(string s, string t) { 8 int m = s.length(), n = t.length(); 9 vector<int> cur(m + 1, 0); 10 for (int j = 1; j <= n; j++) { 11 int pre = 0; 12 for (int i = 1; i <= m; i++) { 13 int temp = cur[i]; 14 cur[i] = (s[i - 1] == t[j - 1] ? pre + 1 : max(cur[i], cur[i - 1])); 15 pre = temp; 16 } 17 } 18 return cur[m]; 19 } 20 21 int main(void) { 22 string s, t; 23 while (getline(cin, s)) { 24 getline(cin, t); 25 printf("%d\n", lcs(s, t)); 26 } 27 return 0; 28 }
Well, try this problem here and get Accepted :)
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 从零开始开发一个 MCP Server!
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Ai满嘴顺口溜,想考研?浪费我几个小时
· Browser-use 详细介绍&使用文档