本文共 4436 字,大约阅读时间需要 14 分钟。
给定一个只包括 '(', ')', '{', '}', '[', ']' 的字符串,判断字符串是否有效。
#include#include using namespace std;class Solution {public: bool isValid(string s) { stack stack_ch; int size = s.size(); for (int i = 0; i < size; ++i) { char ch = s[i]; switch (ch) { case '(': case '{': case '[': { stack_ch.push(ch); break; } case ')': case '}': case ']': { if (stack_ch.empty()) { return false; } char left = stack_ch.top(); if (!((left == '(' && ch == ')') || (left == '[' && ch == ']') || (left == '{' && ch == '}'))) { return false; } stack_ch.pop(); break; } default: { break; } } } return stack_ch.empty(); }};
#includeclass MyStack {public: queue q; MyStack() { } void push(int x) { q.push(x); } int pop() { if (q.empty()) { return -1; // 可按实际需求处理空栈情况 } int size = q.size() - 1; for (int i = 0; i < size; ++i) { int data = q.front(); q.pop(); q.push(data); } int d = q.front(); q.pop(); return d; } int top() { if (q.empty()) { return -1; } int size = q.size() - 1; for (int i = 0; i < size; ++i) { int data = q.front(); q.pop(); q.push(data); } int d = q.front(); q.pop(); q.push(d); return d; } bool empty() { return q.empty(); }};
#includeclass MyQueue {public: stack left; stack right; MyQueue() { } void push(int x) { right.push(x); } int pop() { if (left.empty()) { int size = right.size(); for (int i = 0; i < size; ++i) { int d = right.top(); right.pop(); left.push(d); } } if (left.empty()) { return -1; // 可按实际需求处理空队列情况 } int v = left.top(); left.pop(); return v; } int peek() { if (left.empty()) { int size = right.size(); for (int i = 0; i < size; ++i) { int d = right.top(); right.pop(); left.push(d); } } if (left.empty()) { return -1; // 可按实际需求处理空队列情况 } return left.top(); } bool empty() { return left.empty() && right.empty(); }};
#includeclass MinStack {public: stack normal; stack min; MinStack() { } void push(int x) { normal.push(x); if (min.empty() || x <= min.top()) { min.push(x); } else { min.push(min.top()); } } void pop() { normal.pop(); min.pop(); } int top() { return normal.top(); } int getMin() { return min.top(); }};
#includeclass MyCircularQueue {public: int* array; int size; int capacity; int front; int rear; MyCircularQueue(int k) { array = new int[k]; capacity = k; front = 0; rear = 0; size = 0; } bool enQueue(int value) { if (size == capacity) { return false; } array[rear] = value; rear = (rear + 1) % capacity; size++; return true; } bool deQueue() { if (size == 0) { return false; } front = (front + 1) % capacity; size--; return true; } int Front() { if (size == 0) { return -1; } return array[front]; } int Rear() { if (size == 0) { return -1; } int index = (rear + capacity - 1) % capacity; return array[index]; } bool isEmpty() { return size == 0; } bool isFull() { return size == capacity; }};
转载地址:http://cchoz.baihongyu.com/