算法题——最大子序和And有效的括号
本文介绍两个算法题:数组和字符串方面
1.最大子序和
解法:使用暴力解法,两次迭代
#include<iostream>
using namespace std;
//求数组最大子序和,双迭代
//暴力破解法
int maxNums(int* pt,int numSize){
int max = pt[0];//初始取第一项为最大子序和
for(int i = 0;i<numSize;i++){
int temp = 0;
for(int j = i;j<numSize;j++){
temp += pt[j];
if(temp > max){
max = temp;
}
}
}
return max;
}
int main(){
int nums[] = {-2,1,-3,4,-1,2,1,-5};
cout<<"最大子序和为:"<<maxNums(nums,8)<<endl;
return 0;
}
2.有效的括号
使用栈思路解体,但有一点要特别注意:防止数组下标越界,比如stack1[–top]中的top为负值,会出现无法预料的状况,程序可能不会报错,因此需要做相应处理
#include<iostream>
#include<cstring>//使用strlen()函数
#include<string>
using namespace std;
//有效的括号:解法:栈应用;
bool checkBrackets(char* str){
int len = strlen(str);
cout<<"len:"<<len<<endl;
int top=0;
char stack1[3500] = {0};
for(int i=0;i<len;i++){
if(str[i] == '{'|| str[i] == '(' || str[i] == '['){
stack1[top++] = str[i];
}else{
//没有左括号与之匹配,处理top<=0的情况,防止stack1[--top]出现数组越界,索引为负值,
if(top<=0){
return false;
}
if(str[i]=='}'){
if(stack1[--top] != '{'){
cout<<"{"<<top<<endl;
return false;
}
}
if(str[i]==')'){
if( stack1[--top] != '('){
return false;
}
}
if(str[i]==']'){
if(stack1[--top] != '['){
return false;
}
}
}
}
//没有右括号与左括号与之匹配
if(top>0){
return false;
}
return true;
}
int main(){
char str1[] = "{([])}";
bool checkResult = checkBrackets(str1);
if(checkResult == true){
cout<<"括号配对"<<endl;
}else{
cout<<"括号不配对"<<endl;
}
return 0;
}