File tree Expand file tree Collapse file tree 2 files changed +119
-0
lines changed
Expand file tree Collapse file tree 2 files changed +119
-0
lines changed Original file line number Diff line number Diff line change 1+ //
2+ // Created by mac on 2019/10/28.
3+ //
4+
5+ // 有效的字母异位词
6+ //
7+ // 给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
8+ //
9+ // 示例 1:
10+ //
11+ // 输入: s = "anagram", t = "nagaram"
12+ // 输出: true
13+ // 示例 2:
14+ //
15+ // 输入: s = "rat", t = "car"
16+ // 输出: false
17+ // 说明:
18+ // 你可以假设字符串只包含小写字母。
19+ //
20+ // 进阶:
21+ // 如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?
22+ //
23+ // 来源:力扣(LeetCode)
24+ // 链接:https://leetcode-cn.com/problems/valid-anagram
25+ // 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
26+
27+ // 用了两种方法
28+
29+ // 执行用时: 12 ms, 在所有 cpp 提交中击败了 84.76% 的用户
30+ class SolutionV1 {
31+ public:
32+ bool isAnagram (string s, string t) {
33+ if (s.length () != t.length ()) {
34+ return false ;
35+ }
36+
37+ // todo: 复习 string 容器的使用
38+ unordered_map<char , int > mem;
39+
40+ for (char i : s)
41+ mem[i]++;
42+
43+ for (char i : t)
44+ mem[i]--;
45+
46+ // todo: 复习迭代器的使用
47+ for (auto & iter : mem) {
48+ if (iter.second != 0 )
49+ return false ;
50+ }
51+
52+ return true ;
53+ }
54+ };
55+
56+ // 执行用时: 8 ms, 在所有 cpp 提交中击败了 97.50% 的用户
57+ class SolutionV2 {
58+ public:
59+ bool isAnagram (string s, string t) {
60+ if (s.length () != t.length ()) {
61+ return false ;
62+ }
63+ int table[26 ] = {0 };
64+
65+ for (char i : s) {
66+ table[i - ' a' ]++;
67+ }
68+ for (char i : t) {
69+ table[i - ' a' ]--;
70+ if (table[i - ' a' ] < 0 ) {
71+ return false ;
72+ }
73+ }
74+ return true ;
75+ }
76+ };
Original file line number Diff line number Diff line change 1+ // 爬楼梯
2+ //
3+ // 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
4+ //
5+ // 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
6+ //
7+ // 注意:给定 n 是一个正整数。
8+ //
9+ // 示例 1:
10+ //
11+ // 输入: 2
12+ // 输出: 2
13+ // 解释: 有两种方法可以爬到楼顶。
14+ // 1. 1 阶 + 1 阶
15+ // 2. 2 阶
16+ // 示例 2:
17+ //
18+ // 输入: 3
19+ // 输出: 3
20+ // 解释: 有三种方法可以爬到楼顶。
21+ // 1. 1 阶 + 1 阶 + 1 阶
22+ // 2. 1 阶 + 2 阶
23+ // 3. 2 阶 + 1 阶
24+ //
25+ // 来源:力扣(LeetCode)
26+ // 链接:https://leetcode-cn.com/problems/climbing-stairs
27+ // 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
28+
29+ class Solution {
30+ public:
31+ int climbStairs (int n) {
32+ if (n == 1 ) {
33+ return 1 ;
34+ }
35+ vector<int > dp (n, 0 );
36+ dp[0 ] = 1 ;
37+ dp[1 ] = 2 ;
38+ for (int i = 2 ; i < n; i++) {
39+ dp[i] = dp[i - 1 ] + dp[i - 2 ];
40+ }
41+ return dp[n - 1 ];
42+ }
43+ };
You can’t perform that action at this time.
0 commit comments