1. 最长连续递增子序列
题目

代码
#include <cstdio>
#include <string>
#include <map>
#include <vector>
using namespace std;
//substr 左右都是闭区间
int main(){
// 处理输入
int n;
scanf("%d",&n);
int nums[n];
for(int i=0;i<n;i++){
scanf("%d",&nums[i]);
}
// 算法设计
int ans = 0;
int start = 0; // 连续递增序列的开始下标
for(int i=0;i<n;i++){
// 前一个元素 >= 后一个元素 那么不是递增序列,更新start起始下标
// 前一个元素 < 后一个元素 start不变,i继续后移
if(i>0 && nums[i] <= nums[i-1]){
start = i;
}
ans = max(ans,i-start+1);
}
// 打印输出
printf("%d",ans);
}
2.最长公共前缀
题目:

代码:
#include <cstdio>
#include <string>
#include <map>
#include <vector>
using namespace std;
//substr 左右都是闭区间
int main(){
// 处理输入
int n;
int len=0;
scanf("%d",&n);
string nums[n];
// 最长字符长度
for(int i=0;i<n;i++){
char strs[100];
scanf("%s",strs);
string numstr = strs;
len = max(len,int(numstr.length()));
nums[i] = numstr;
}
// 填充其他字符到一样的长度
for(int i=0;i<n;i++){
int a = nums[i].length();
while(a<len){
nums[i][a] = ',';
a++;
}
}
// 对比每个字符
for(int i=0;i<len;i++){
char c = nums[0][i];
// 遍历字符串
for(int j=1;j<n;j++){
// 如果这一列的元素都相等,则什么都不做
// 如果有一个不相等,截取并输出
if(nums[j][i] != c){
printf("%s",nums[0].substr(0,i).c_str());
return 0;
}
}
}
printf("%s",nums[0].c_str());
}
3.有效的括号
题目:

代码:
#include <cstdio>
#include <string>
#include <map>
#include <vector>
#include <stack>
using namespace std;
//substr 左右都是闭区间
int main(){
char cstr[200];//c风格字符串
scanf("%s",cstr);
string str = cstr; //c-->c++
int n = str.size();
// 如果是奇数,则直接返回false
if(n%2==1){
printf("false");
}
// 声明map时记得加分号
map<char,char> pairs = {
{')', '('},
{']', '['},
{'}', '{'}
};
stack<char> stk;
// 遍历每个字符
for(int i=0;i<n;i++){
char ch = str[i];
// 如果遇到左括号 压栈
if(ch=='(' || ch=='{' || ch=='['){
stk.push(ch);
}
//如果遇到右括号
if(ch==')' || ch=='}' || ch==']'){
if(pairs[ch] == stk.top()){
stk.pop();
}
else{
printf("false");
return 0;
}
}
}
// 如果匹配完成之后, 栈中还有剩余
if(stk.empty()){
printf("true");
return 0;
}
else{
printf("false");
return 0;
}
}
4. 删除有序数组中的重复项
题目:


代码:
#include <cstdio>
#include <string>
#include <map>
#include <vector>
#include <stack>
using namespace std;
//substr 左右都是闭区间
int main(){
// 处理输入
int n;
scanf("%d",&n);
int nums[n];
for(int i=0;i<n;i++){
scanf("%d,",&nums[i]);
}
//删除重复项
int j=0;
for(int i=1;i<n;i++){
// 如果这个元素与下一个元素不相等,保存这个数字
if(nums[j]!=nums[i]){
nums[++j]=nums[i];
}
// 否则j不变,i继续递增
}
printf("%d\n",j+1);
for(int i=0;i<=j;i++){
printf("%d ",nums[i]);
}
}
本文提供了四个C++代码示例,分别解决经典的算法问题:找出数组中的最长连续递增子序列、计算字符串数组的最长公共前缀、验证给定字符串是否为有效括号组合以及删除有序数组中的重复元素。这些代码利用了基本的数组操作、字符串处理和栈数据结构。

被折叠的 条评论
为什么被折叠?



