0 有效的括號
class Solution {
public boolean isValid(String s){
Stack<Character> stack = new Stack<Character>();
for(char c : s.toCharArray()){
if(c == '(')
stack.push(')');
else if(c == '[')
stack.push(']');
else if(c == '{')
stack.push('}');
else if(stack.isEmpty() || c != stack.pop())
return false;
}
return stack.isEmpty();
}
}
1 兩個扭蛋機
import java.util.Scanner;
/*思路:正向向上加到 N,比較難辦到;但是倒着想,就好辦多了;
首先肯定是優先3號機,N減小得快;*/
public class Main {
static void help(int n, StringBuffer buffer) {
if (n<=0) {
return;
}
if (n%2==0) {
buffer.append('3');
help((n-2)/2, buffer);
}else {
buffer.append('2');
help((n-1)/2, buffer);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
StringBuffer buffer = new StringBuffer();
int n;
n = scanner.nextInt();
help(n, buffer);
System.out.println(new String(buffer.reverse()));
}
}
2 求第k
個僅出現一次的字符
#include <iostream>
#include <string>
#include <list>
#include <unordered_map>
using namespace std;
int main(){
int k;
string s;
while(scanf("%d", &k) != EOF){
int count = 0;
string s;
getchar();
getline(cin, s);
unordered_map<char, int> hash;
list<char> ch;
for(int i = 0; i < s.size(); i++){
hash[s[i]]++;
ch.push_back(s[i]);
}
//去掉重複元素(從後向左)
ch.unique();
for(auto it = ch.begin(); it != ch.end(); it++){
if(hash[*it] == 1)
count++;
if(count == k){
cout<<"["<<*it<<"]"<<endl;
break;
}
}
if(count != k)
cout<<"Myon~"<<endl;
}
return 0;
}
3 基本計算器II(leetcod227、772)
實現一個基本的計算器來計算一個簡單的字符串表達式的值。字符串表達式僅包含非負整數,+
, -
,*
,/
四種運算符和空格
。 整數除法僅保留整數部分。
import java.util.LinkedList;
import java.util.Stack;
public class Solution{
public int calculate(String exp) {
return calRst(backTempExp(exp));
}
// 計算後綴表達式
public static LinkedList<String> backTempExp(String exp) {
Stack<String> stkEles = new Stack<String>();
LinkedList<String> tempBackExp = new LinkedList<String>();
for (int i = 0; i < exp.length(); i++) {
// 1.遇到了數字
if (Character.isDigit(exp.charAt(i))) {
// 注意多位數的獲取
int k = i + 1;
for (; k < exp.length() && Character.isDigit(exp.charAt(k)); k++) {
}
tempBackExp.add(exp.substring(i, k));
i = k - 1;// 更新 i
continue;
}
// 2.遇到了乘除運算符
if (exp.charAt(i) == '/' || exp.charAt(i) == '*') {
while (!stkEles.isEmpty() && (stkEles.lastElement().equals("/") || stkEles.lastElement().equals("*"))) {
tempBackExp.add(stkEles.pop()); // 彈出優先級相同或以上的棧內運算符
}
stkEles.add(String.valueOf(exp.charAt(i))); // 運算符入棧
continue;
}
// 3.遇到了加減運算符
if (exp.charAt(i) == '+' || exp.charAt(i) == '-') {
while (!stkEles.isEmpty() && !isNumeric(stkEles.lastElement())) {
tempBackExp.add(stkEles.pop()); // 彈出優先級相同或以上的棧內運算符
}
stkEles.add(String.valueOf(exp.charAt(i))); // 運算符入棧
continue;
}
}
// 4.最後彈出棧內所有元素到表達式
while (stkEles.size() > 0) {
tempBackExp.add(stkEles.pop());
}
return tempBackExp;
}
// 計算最終的結果
public static int calRst(LinkedList<String> tempBackExp) {
Stack<Integer> calStk = new Stack<Integer>();
for (String c : tempBackExp) {
// 1.數字,入棧
if (isNumeric(c)) {
calStk.push(Integer.valueOf(c)); // string to int
continue;
}
// 2.非數字,則爲符號,出棧兩個元素計算出結果然後再入棧該計算值
else {
int a = calStk.pop();
int b = calStk.pop();
switch (c.toCharArray()[0]) {
// 注意減法和除法時,注意出棧的順序與原表達式是相反的
case '+':
calStk.push(b + a);
continue;
case '-':
calStk.push(b - a);
continue;
case '*':
calStk.push(b * a);
continue;
case '/':
calStk.push(b / a);
continue;
}
}
}
return calStk.pop();
}
public static boolean isNumeric(String str) {
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
}
另一種:只有+-*三種運算符
#include <iostream>
#include <vector>
using namespace std;
int main(){
string s;
cin>>s;
while(s != "END"){
// 存每個數
vector<string> numbers;
// 存操作符
vector<char> operate;
// 先解決乘除法
for(int i = 0; i < s.size(); i++){
// 是數字
if(s[i] >= '0' && s[i] <= '9'){
// 存儲一個數字
string nowN;
nowN += s[i];
i++;
for(; i < s.size(); i++){
if(s[i] >= '0' && s[i] <= '9')
nowN += s[i];
else{
i--;
break;
}
}
numbers.push_back(nowN);
}
// 乘號
else if(s[i] == '*'){
// 找到下一個數
string nowN;
i++;
for(; i < s.size(); i++){
if(s[i] >= '0' && s[i] <= '9')
nowN += s[i];
else{
i--;
break;
}
}
// 轉換爲整數
int nowInt = std::stoi(nowN);
int lastInt = std::stoi(numbers[numbers.size() - 1]);
numbers.pop_back();
numbers.push_back(to_string(nowInt * lastInt));
}
// 加減號
else{
operate.push_back(s[i]);
}
}
// 最後處理
int ans = std::stoi(numbers[0]);
// 刪除第一個
numbers.erase(numbers.begin());
for(int i = 0; i < operate.size(); i++){
if(operate[i] == '+'){
ans += std::stoi(numbers[0]);
// 刪除第一個
numbers.erase(numbers.begin());
}
else if(operate[i] == '-'){
ans -= std::stoi(numbers[0]);
// 刪除第一個
numbers.erase(numbers.begin());
}
}
printf("%d\n", ans);
cin>>s;
}
return 0;
}
4 基本計算器(leetcode224)
class Solution {
public:
// 可測試3-(4+5)+6
int calculate(string s) {
stack<int> st;
int res = 0;
int n = s.size();
// 默認表示+
int sign = 1;
for(int i = 0; i < n; i++) {
int num = 0;
if(s[i] >= '0') {
while(i < n && s[i] >= '0') {
num = num * 10 + (s[i] - '0');
i++;
}
i--;
res += sign * num;
}
else if(s[i] == '+') sign = 1;
else if(s[i] == '-') sign = -1;
else if(s[i] == '(') {
st.push(res);
st.push(sign);
res = 0;
sign = 1;
}
else if(s[i] == ')') {
res *= st.top();
st.pop();
res += st.top();
st.pop();
}
}
return res;
}
};
5 新認識的人(深度優先搜索DFS)
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 8;
vector<int> G[maxn];
int res = 0;
//深度遍歷 找到一個集合的人
void dfs(int ai, vector<bool> &v) {
for (int i = 0; i < G[ai].size(); ++i) {
if (!v[G[ai][i]]) {
v[G[ai][i]] = true;
res++;
dfs(G[ai][i], v);
}
}
}
int main() {
int n, ai, m;
cin >> n >> ai >> m;
//構建鄰接表
while (m--) {
int p1, p2;
char chs;
cin >> p1 >> chs >> p2;
G[p1].push_back(p2);
G[p2].push_back(p1);
}
vector<bool> visited(n + 1, false);
//除去本來就認識的人和自己
int already = G[ai].size() + 1;
dfs(ai,visited);
cout << res - already << endl;
return 0;
}
6 數組中3數之和爲某個數
#include <bits/stdc++.h>
using namespace std;
int main(){
int n,x;
vector<int> v;
while(cin>>x){
v.push_back(x);
if(getchar()==',')
break;
}
cin>>n;
sort(v.begin(), v.end());
int m = v.size(), l, r;
for(int i = 1;i <= m - 2; i++){
l = 0;
r = m - 1;
while(l < i && r > i){
if(v[l]+v[r]+v[i] == n){
cout<<"True"<<endl;
return 0;
}else if(v[l]+v[r]+v[i] < n)
l++;
else
r--;
}
}
cout<<"False"<<endl;
return 0;
}
7 酒杯
#include <bits/stdc++.h>
using namespace std;
int main(){
int n, k;
scanf("%d", &n);
vector<int> ans(n, 0);
for(int i = 0 ; i < n; i++)
scanf("%d", &ans[i]);
scanf("%d", &k);
sort(ans.begin(), ans.end());
int left = 0;
int right = n - 1;
bool flag = true;
while(left < right){
if(ans[left] + ans[right] == k){
cout<<ans[left]<<" "<<ans[right]<<endl;
left++;
//right--;
flag = false;
}
else if(ans[left] + ans[right] > k)
right--;
else
left++;
}
if(flag)
printf("NO\n");
return 0;
}
8 LeetCode【1004】最大連續1的個數 III
public static int longestOnes(int[] A, int K) {
int left = 0, right = 0;
int max = 0;
int zero = 0;
while (right != A.length) {
if (A[right++] == 0) {
zero++;
}
//判定條件,0的個數大於K
while (zero > K) {
if (A[left++] == 0) {
--zero;
}
}
int count = right - left;
max = max > count ? max : count;
}
return max;
}