基础算法-c/c++

Posted 我的头发可没乱

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基础算法-c/c++相关的知识,希望对你有一定的参考价值。




给出一个仅包含字符'(',')','{','}','['和']',的字符串,判断给出的字符串是否是合法的括号序列
括号必须以正确的顺序关闭,"()"和"()[]{}"都是合法的括号序列,但"(]""([)]"不合法

class Solution {public: /** *  * @param s string字符串  * @return bool布尔型 */ bool isValid(string s) { stack<char> st; for(auto&i:s){ if(!st.empty()){ if((i==']'&&st.top()=='[')||(i=='}'&&st.top()=='{')||(i==')'&&st.top()=='(')){ st.pop(); continue; } } st.push(i); } return st.empty(); }};


//2222class Solution {public: /** * * @param s string字符串 * @return bool布尔型 */ bool isValid(string s) { // write code here int hall ,i; char *str_hall= (char *)(malloc(sizeof(s)+2)); char char_ ; for(i=0,hall=0; i<s.size(); i++) switch (s[i]) { case'{':str_hall[++hall]='{';break; case'[':str_hall[++hall]='[';break; case'(':str_hall[++hall]='(';break; case '}':if(str_hall[hall]=='{'){hall--;break;} case ']':if(str_hall[hall]=='['){hall--;break;} case ')':if(str_hall[hall]=='('){hall--;break;} free(str_hall); return false; } if(hall)return false; else free(str_hall); return true ; }};

给定一个二叉树,返回该二叉树的之字形层序遍历,(第一层从左向右,下一层从右向左,一直这样交替)
例如:
给定的二叉树是{3,9,20,#,#,15,7},

/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */
class Solution {public: /** * * @param root TreeNode类 * @return int整型vector<vector<>> */ vector<vector<int> > zigzagLevelOrder(TreeNode* root) { vector<vector<int> > v; if(root == nullptr) return v; queue<TreeNode*> q; q.push(root); int f = 1; //标识是否翻转 while(!q.empty()) { vector<int> v1; //暂存每一层 int s = q.size(); while(s--) { TreeNode* t = q.front(); q.pop(); v1.push_back(t->val); if(t->left) q.push(t->left); if(t->right) q.push(t->right); } if(f == -1) reverse(v1.begin(), v1.end()); v.push_back(v1); f *= -1; } return v; }};


给定两个字符串str1和str2,输出两个字符串的最长公共子串

题目保证str1和str2的最长公共子串存在且唯一。

/** * longest common substring * @param str1 string字符串 the string * @param str2 string字符串 the string * @return string字符串 */char* LCS(char* str1, char* str2 ) { int len1=strlen(str1); int len2=strlen(str2); int i,j,k; int max_len=0; int a=-1; for(i=0;i<len1;i++){ for(j=0;j<len2;j++){ if(str1[i]==str2[j]){ for(k=1;(i+k<len1)&&(j+k<len2);k++){ if(str1[i+k]!=str2[j+k]){ break; } } if(k>max_len){ max_len=k; a=i; } } } } str1[a+max_len]=''; return str1+a;}


int* spiralOrder(int** matrix, int matrixRowLen, int* matrixColLen, int* returnSize ) { // write code here
if(matrixRowLen == 0) { return NULL; }
int rows = matrixRowLen; int columns = *matrixColLen; int count = rows * columns;
int sizeInt = sizeof(int);
int *result = (int*)malloc(sizeInt * count);
for(int i = 0, r = 0, c = 0, row = rows-1, col = columns-1; r <= row && c <= col;) { // int length = col - c + 1; // memcpy(result + i * sizeInt, matrix[r] + c * sizeInt, sizeInt * length); // i += length; // r++; for(int cc = c; cc <= col; cc++, i++) { result[i] = matrix[r][cc]; } r++;
for(int rr = r; rr <= row; rr++, i++) { result[i] = matrix[rr][col]; } col--;
if(r <= row) { for(int cc = col; cc >= c; cc--, i++) { result[i] = matrix[row][cc]; } } row--;
if(c <= col) { for(int rr = row; rr >= r; rr--, i++) { result[i] = matrix[rr][c]; } } c++; }
*returnSize = count;
return result;}

基础算法-c/c++(4)

/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) { int n = pre.size(); int m = vin.size(); if(n!=m || n == 0) return NULL; return construct(pre, vin, 0, n-1, 0, m-1); }  TreeNode* construct(vector<int>& pre, vector<int>& vin, int l1, int r1, int l2, int r2){ TreeNode* root = new TreeNode(pre[l1]); if(r1 == l1) { return root; } int val = pre[l1]; int index; for(index = l2; index <= r2; index ++) { if(vin[index] == val) break; } int left_tree_len = index - l2; int right_tree_len = r2 - index; if(left_tree_len > 0) root->left = construct(pre, vin, l1+1, l1+left_tree_len, l2, index-1); if(right_tree_len >0 ) root->right = construct(pre, vin, l1+1+left_tree_len, r1, index+1, r2); return root; }};

基础算法-c/c++(4)

int Fibonacci(int n){ int j; int num[40]; num[0]=0; num[1]=1; for(int i=2;i<40;i++) { num[i]=num[i-1]+num[i-2]; } return num[n];}

基础算法-c/c++(4)

class Solution {public: int getLongestPalindrome(string A, int n) { int res=0; for(int i=0; i<A.size();++i){ int left=i; while(i<n-1 && A[i+1]==A[i]){ ++i; } int right = i; while(left>=0 && right<n && A[left]==A[right]){ left--;right++; } res=max(res,right-left-1); }  return res; }};

基础算法-c/c++(4)

/** * max water * @param arr int整型一维数组 the array * @param arrLen int arr数组长度 * @return long长整型 */long long maxWater(int* arr, int arrLen ) { // write code here if(arrLen <= 2) return 0;  int i = 0; int j = arrLen - 1;  int maxLeft = arr[i]; int maxRight = arr[j];  long sum = 0L;  while(i < j) { if(maxLeft < maxRight) { i++; if(arr[i] > maxLeft){ maxLeft = arr[i]; } else { sum += maxLeft - arr[i]; } } else { j--; if(arr[j] > maxRight) { maxRight = arr[j]; } else { sum += maxRight - arr[j]; } } }  return sum;}

基础算法-c/c++(4)

struct Node{ int val; Node *left; Node *right; Node(int x=0):val(x),left(nullptr),right(nullptr){};};class Solution {public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * 求二叉树的右视图 * @param xianxu int整型vector 先序遍历 * @param zhongxu int整型vector 中序遍历 * @return int整型vector */ Node* buildTree(vector<int> &pre,vector<int> &mid,int le1,int ri1,int le2,int ri2){ if(le1>ri1||le1-ri1!=le2-ri2) return 0; int index=le2; //首地址 while(mid[index]!=pre[le1]) { ++index; //在中序遍历中首先寻找根节点(前序的第一个数) 该下标的左边的数为左子树,右边的数位右子树 } Node *p=new Node(pre[le1]); //前序的第一个数为根节点 p->left=buildTree(pre,mid,le1+1,le1+index-le2,le2,index-1); //卡出前序和中序遍历中的左子树的部分(前后下标值) p->right=buildTree(pre,mid,le1+index-le2+1,ri1,index+1,ri2); //卡出前序和中序遍历中的右子树的部分(前后下标值) return p; } vector<int> solve(vector<int>& xianxu, vector<int>& zhongxu) { // write code here  //通过前序和后序重建树结构 Node *head=buildTree(xianxu,zhongxu, 0,xianxu.size()-1,0,zhongxu.size()-1); //res用以存放右视图的值val vector<int> res; if(head==0) return res; //队列用以存放树,实现层序遍历 queue<Node*> q; q.push(head); while(!q.empty()) { Node *temp=q.front(); res.push_back(temp->val); for(int i=q.size();i>0;i--) { temp=q.front(); q.pop(); if(temp->right) q.push(temp->right); if(temp->left) q.push(temp->left); } } return res; }};

基础算法-c/c++(4)

/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 *  * @param str string字符串 待判断的字符串 * @return bool布尔型 */#include <stdbool.h>
bool judge(char* str ) { // write code here int len = strlen(str); int left = 0; int right = len - 1; while (left < right) { if (str[left] == str[right]) { left++; right--; } else { return false; } } return true;}

基础算法-c/c++(4)

#include <stdbool.h>#include <math.h>/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */
/** * * @param pRoot TreeNode类 * @return bool布尔型 */ int depth(struct TreeNode* pRoot){ if(!pRoot) return 0; int ldepth=depth(pRoot->left); if(ldepth==-1) return-1; int rdepth=depth(pRoot->right); if(rdepth==-1) return -1; int sub=abs(ldepth-rdepth); if(sub>1) return -1; return (ldepth>rdepth? ldepth:rdepth)+1; } bool IsBalanced_Solution(struct TreeNode* pRoot ) { // write code here return depth(pRoot)!=-1;}

基础算法-c/c++(4)

class Solution {public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * 返回表达式的值 * @param s string字符串 待计算的表达式 * @return int整型 */ int solve(string s) { // write code here stack<int> stk; int n = s.size(); int num = 0, result = 0; char flag = '+'; for(int i = 0; i < n; i++){ char c = s[i]; if(c <= '9' && c >= '0') num = num * 10 + c -'0'; if(c == '('){ int j = i + 1; int count = 1; while(count){ if(s[j] == ')') count--; else if(s[j] == '(') count++; j++; } num = solve(s.substr(i + 1, j - i - 1)); i = j - 1; } if(c == '(' || c == ')' || c == '+' || c == '-' || c == '*' || i == n - 1){ if(flag == '+') stk.push(num); if(flag == '-') stk.push(-num); if(flag == '*'){ num *= stk.top(); stk.pop(); stk.push(num); } flag = c; num = 0; } } while(!stk.empty()){ result += stk.top(); stk.pop(); } return result; }};

基础算法-c/c++(4)

/** * find median in two sorted array * @param arr1 int整型一维数组 the array1 * @param arr1Len int arr1数组长度 * @param arr2 int整型一维数组 the array2 * @param arr2Len int arr2数组长度 * @return int整型 */int findMedianinTwoSortedAray(int* arr1, int arr1Len, int* arr2, int arr2Len ) { int len=(arr1Len+arr2Len); if(len%2) { len=len>>1+1; } else { len=len>>1; } int *array=(int*)calloc(len,sizeof(int)); int i=0,m=0,n=0; while(i<len) {  if(arr1[m]>arr2[n]) { array[i]=arr2[n]; n++; } else { array[i]=arr1[m]; m++; } i++; } return array[i-1];  // write code here}

基础算法-c/c++(4)

class Solution {public: int atoi(const char *str) { int sum = 0, idx = 0, sign = 1; while(str[idx] != '' && str[idx] == ' ') ++idx;//去除空格 if(str[idx] == '-'){ sign = -1; ++idx; } else if(str[idx] == '+') ++idx; while(str[idx] != ''){ if(str[idx] > '9' || str[idx] < '0') break; if((sum > INT_MAX / 10) || ((sum == INT_MAX / 10) && (str[idx] - '0' > INT_MAX % 10))){ return sign == 1 ? INT_MAX : INT_MIN; } sum = sum * 10 + str[idx] - '0'; ++idx; } return sum * sign; }};

基础算法-c/c++(4)

class Solution {public: /** *  * @param s string字符串  * @return string字符串vector */ vector<string> res; vector<string> restoreIpAddresses(string s) { int n = s.size(); string cur = s; helper(n,0,-1,cur,s); return res; } void helper(int n,int pointnum,int lastpoint,string& cur,string& s) { //pointnum记录目前加了几个点了,lastpoint记录上一个点加的位置 if (pointnum == 3) { //如果已经加了三个点了,并且最后一个点的右边表示的数小于255,则是正确IP地址 if (valid(lastpoint + 1,n-1,s)){ res.push_back(cur); } return; } //从上一个.号的下一个位置开始查找 for (int i = lastpoint + 1;i < n - 1;i++) { //如果字符串s从上一个.号到i位置表示的数小于等于255,则符合条件 if (valid(lastpoint + 1,i,s)){ //正常回溯法,注意这里要+pointnum,因为已经加入的.号也会占位 cur.insert(cur.begin() + i + pointnum + 1,'.'); helper(n,pointnum + 1,i,cur,s); cur.erase(pointnum + i + 1,1); } } return; } bool valid(int left,int right,string& s) { int sum = 0; for (int i = left ;i <= right; i++) { //处理0开头问题 if (left != right && s[left] == '0' ) return false; //计算字符串s中left到right位表示的数的大小 sum = sum *10 + (s[i] - '0'); if (sum > 255) return false; } return true; }};

基础算法-c/c++(4)


/*struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { }};*/class Solution {public: char* Serialize(TreeNode *root) {  if (root == nullptr) { return "#"; }  string res = to_string(root->val); res.push_back(',');  char* left = Serialize(root->left); char* right = Serialize(root->right);  char* ret = new char[strlen(left)+strlen(right)+res.size()]; // 如果是string类型,直接用operator += ,这里char* 需要用函数 strcpy(ret,res.c_str()); strcat(ret,left); strcat(ret,right);  return ret; }  TreeNode* deserialize(char* &s){ if (*s == '#') { ++s; return nullptr; }  // 构造根节点值 int num = 0; while (*s != ',') { num = num * 10 + (*s - '0'); ++s; } ++s; // 递归构造树 TreeNode *root = new TreeNode(num); root->left = deserialize(s); root->right = deserialize(s);  return root; } TreeNode* Deserialize(char *str) { return deserialize(str); }};

基础算法-c/c++(4)

class Solution {public: /** * max increasing subsequence * @param arr int整型vector the array * @return int整型 */ int MLS(vector<int>& arr) { // write code here sort(arr.begin(), arr.end()); int max = 1; int length = 1; for(int i = 1; i < arr.size(); i++) { if(arr[i] - 1 == arr[i - 1]) { length++; } else if(arr[i] != arr[i - 1]) { length = 1; } max = std::max(max, length); } return max; }};

基础算法-c/c++(4)

/** *  * @param s string字符串  * @param n int整型  * @return string字符串 */char* trans(char* s, int n ) { char str[501][50] = {0}; int m = 0; int i = 0; for(i = 0; i < n ; i++) { if(s[i] == ' ') { str[m++][0] = ' '; } else { s[i] = islower(s[i]) ? toupper(s[i]) : tolower(s[i]); strncat(str[m],&s[i],1); s[i+1] == ' '? m++ : 0; } } memset(s,0,sizeof(char)*n); for(i = m ; i >= 0 ; i--) { strcat(s,str[i]); } return s; }

基础算法-c/c++(4)

class Solution {public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * *  * @param str string字符串  * @param pattern string字符串  * @return bool布尔型 */ bool matchCore(char * str, char * pattern) { if(*str == '' && *pattern == '') return true; if(*(pattern+1) == '*') { //字符相等*代表多个字符 || *代表一个字符 || *代表0个字符 //字符不等 *代表0个字符 if(*pattern == *str || (*pattern == '.' && *str != '')) return matchCore(str + 1, pattern) || matchCore(str+1, pattern+2) ||matchCore(str, pattern+2); else return matchCore(str , pattern+2); } if(*str == *pattern || (*pattern == '.' && *str != '') ) return matchCore(str+1, pattern+1);   return false; }  bool match(string str, string pattern) { // write code here return matchCore(&str[0], &pattern[0]);  }};

基础算法-c/c++(4)

/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 如果目标值存在返回下标,否则返回 -1 * @param nums int整型一维数组  * @param numsLen int nums数组长度 * @param target int整型  * @return int整型 */int search(int* nums, int numsLen, int target ) { // write code here int high=numsLen,low=0; if(numsLen==0) return -1; while(low<high){ int mid=(high+low)/2; if(nums[mid]==target) high=mid; else if(nums[mid]<target){ low=mid+1; } else if(nums[mid]>target){ high=mid; } } if(nums[low]==target) return low; else return -1;}

基础算法-c/c++(4)

class Solution {public: bool isMatch(const char *s, const char *p) { int sLen = strlen(s),sIndex = 0; int pLen = strlen(p),pIndex = 0; int ppre = 0,ipre = 0; bool flag = false; while (sIndex<sLen) { if (s[sIndex]==p[pIndex] || p[pIndex]=='?'){ ++sIndex,++pIndex; }else if (p[pIndex]=='*'){ //跳过并记录*后面开始匹配的索引 ppre = ++pIndex; ipre = sIndex; //记录s中开始与*后面匹配的索引 flag = true; }else{ if (flag){ //无法匹配,在出现*情况下用*弥补 sIndex = ++ipre; pIndex = ppre; }else{ return false; } } } while (p[pIndex]=='*') { //将剩余的*匹配掉 ++pIndex; } return pIndex==pLen&&sIndex==sLen; }};

基础算法-c/c++(4)

/** * struct ListNode { * int val; * struct ListNode *next; * }; *//** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * *  * @param pHead ListNode类  * @param k int整型  * @return ListNode类 */struct ListNode* FindKthToTail(struct ListNode* pHead, int k ) { // write code here struct ListNode *Last, *arr[888]; int cnt = 0; for(Last=pHead; Last; Last=Last->next) arr[ cnt++ ] = Last;  if(k > cnt) return NULL;  return arr[ cnt-k ];}

class Solution {public: long long subsequence(int n, vector<int>& array) { long long excl = 0, incl = 0; for (int i = 0; i < n; ++i) { int old_excl = excl; excl = max(excl, incl); incl = old_excl + array[i]; } return max(excl, incl); }};





个人笔记本

新浪微博|我的头发可没乱


以上是关于基础算法-c/c++的主要内容,如果未能解决你的问题,请参考以下文章

[linux][c/c++]代码片段01

[linux][c/c++]代码片段02

c/c++面试总结---c语言基础算法总结2

爆肝一周——PYTHON 算法基础

2020牛客寒假算法基础集训营5.C——C语言IDE超级大模拟

C/C++编程基础算法总结