LeetCode383. Ransom Note优雅解法(线性时间复杂度)
2016-08-29 23:46
525 查看
Given
an
arbitrary
ransom
note
string
and
another
string
containing
letters from
all
the
magazines,
write
a
function
that
will
return
true
if
the
ransom
note
can
be
constructed
from
the
magazines ;
otherwise,
it
will
return
false.
Each letter in the magazine string can only be used once in your ransom note.
Note:
You may assume that both strings contain only lowercase letters.
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int pool[26] = {0};
for (char c : magazine) {
pool[c-'a']++;
}
for (char c : ransomNote) {
if (pool[c-'a'] > 0) {
pool[c-'a']--;
} else {
return false;
}
}
return true;
}
};
false.
Each letter in the magazine string can only be used once in your ransom note.
Note:
You may assume that both strings contain only lowercase letters.
canConstruct("a", "b") -> false canConstruct("aa", "ab") -> false canConstruct("aa", "aab") -> true
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int pool[26] = {0};
for (char c : magazine) {
pool[c-'a']++;
}
for (char c : ransomNote) {
if (pool[c-'a'] > 0) {
pool[c-'a']--;
} else {
return false;
}
}
return true;
}
};
相关文章推荐
- 求最大子序列的线性时间复杂度的解法的理解
- LeetCode 383. Ransom Note 自己的解法
- Leetcode 234 Palindrome Linked List 复杂度为时间O(n) 和空间(1)解法
- Leetcode 234 Palindrome Linked List 复杂度为时间O(n) 和空间(1)解法
- 长度为n的顺序表L,编写一个时间复杂度为O(n),空间复杂度为O(1)的算法,该算法删除线性表中所有值为X的元素
- MIT:算法导论——2.渐近符号、递归及解法_和连续子数组的最大和、主方法/主定理求时间复杂度
- 线性时间复杂度求数组中第K大数
- 线性时间复杂度求数组第n大
- 无序数组A和B,线性时间复杂度,空间复杂度O(1) ,求中位数
- 大话数据结构-时间复杂度,线性表,栈,队列
- 动态规划小结 - 一维动态规划 - 时间复杂度 O(n),题 [LeetCode] Jump Game,Decode Ways
- 线性时间复杂度求数组中第K大数
- Candy [leetcode] O(n)时间复杂度,O(1)空间复杂度的方法
- Candy [leetcode] O(n)时间复杂度,O(1)空间复杂度的方法
- Candy [leetcode] O(n)时间复杂度,O(1)空间复杂度的方法
- 查找与排序01,线性查找,时间复杂度,算法
- 计数排序算法!线性时间复杂度!
- 线性O(N)时间复杂度求素数 , 筛法
- 给一个由n-1个整数组成的未排序的序列,其元素都是1~n中的不同的整数。如何在线性时间复杂度内寻找序列中缺失的整数
- Submission Details [leetcode] ---- inplace 线性时间 的两种思路