今天完成了三道题目,总结一下:
1: Length of last word(细节实现题)
此题有一些细节需要注意(比如 “a_ _” 最后一个单词是a, 而不是遇到空格就直接算成没有),别的基本就是模拟了。
1 class Solution {
2 public:
3 int lengthOfLastWord(const char *s) {
4 string str = s;
5 if(str.empty()) return 0;
6 int index;
7 // 从后向前扫描到第一个不是空格的字符
8 for(index = str.size()-1;index>=0;index--)
9 {
10 if(str[index]!=‘ ‘)
11 break;
12 }
13 if(index<0) return 0;
14 int i;
15 //从此字符开始,往前遇到空格停止计算或者把字符串扫描完
16 for(i=index;i>=0;i--)
17 {
18 if(str[i] == ‘ ‘)
19 break;
20 }
21 return (index-i);
22 }
23 };
2. Trapping Rain Water
Given n non-negative integers representing an elevation
map where the width of each bar is 1, compute how much water it is able to trap
after raining.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1]
,
return 6
.
这道题目是直方图类题目,贴出的解法是book上的,两轮扫描,第一轮记录左前缀最大值和右前缀最大值; 第二轮扫描,对每个位置,可以积的水是
max(min(max_left,max_right)-height,0) height 是当前位置的格子高度。
这道题目应该算是一道技巧题了。
1 class Solution {
2 public:
3 int trap(int A[], int n) {
4 if(n<2) return 0;
5 int* left_max = new int[n];
6 int* right_max = new int[n];
7
8 // Two pass algorithm
9 left_max[0] = A[0];
10 right_max[n-1] = A[n-1];
11 for(int i=1;i<n;i++)
12 {
13 left_max[i] = max(left_max[i-1],A[i]);
14 right_max[n-1-i] = max(right_max[n-i],A[n-1-i]);
15 }
16 int water = 0;
17 for(int i=0;i<n;i++)
18 {
19 water += max(min(left_max[i],right_max[i])-A[i],0);
20 }
21 return water;
22
23 }
24 };
View
Code
3.Valid Parentheses
Given a string containing just the
characters ‘(‘
, ‘)‘
, ‘{‘
, ‘}‘
, ‘[‘
and ‘]‘
,
determine if the input string is valid.
The brackets must close in the correct
order, "()"
and "()[]{}"
are all
valid but "(]"
and "([)]"
are
not.
简单的括号匹配题,一般都是用栈来实现。实现细节要注意,错误都犯在控制变量的初始化上了(test 变量每次set成true之后,没有重新初始化)
1 class Solution {
2 public:
3 bool isValid(string s) {
4 stack<int> st;
5 bool test=false;int num;
6 for(int i=0;i<s.size();i++)
7 {
8 switch (s[i])
9 {
10 case ‘(‘: num = 1;st.push(num);break;
11 case ‘[‘: num = 2;st.push(num);break;
12 case ‘{‘: num = 3;st.push(num);break;
13 case ‘)‘: num = 1;test = true;break;
14 case ‘]‘: num = 2;test =true;break;
15 case ‘}‘: num = 3;test = true; break;
16 }
17 if(test)
18 {
19 if(st.empty() || st.top()!=num) return false;
20 else st.pop();
21 test =false;
22 }
23 }
24 if(st.empty()) return true;
25 else return false;
26 }
27 };