国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

LEETCODE--Ransom Note

2019-11-14 12:55:21
字體:
來源:轉載
供稿:網友

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. canConstruct(“a”, “b”) -> false canConstruct(“aa”, “ab”) -> false canConstruct(“aa”, “aab”) -> true 方法一:先排序后再進行匹配;

class Solution {public: bool canConstruct(string ransomNote, string magazine) { sort(ransomNote.begin(), ransomNote.end()); sort(magazine.begin(), magazine.end()); int i = 0; int j = 0; while(i < ransomNote.length() && j < magazine.length()){ if(ransomNote[i] == magazine[j]){ cout << ransomNote[i] << endl;; i++; } j++; } if(i == ransomNote.length()) return 1; else return 0; }};

方法二: 使用標記數組A,因為可能出現的字符只有26個(是有限的)。A中的元素表示magazine中相應字符出現的次數.

class Solution {public: bool canConstruct(string ransomNote, string magazine) { int A[26] = {0}; int rlen = ransomNote.length(); int mlen = magazine.length(); for(int i = 0; i < mlen; i++) ++A[magazine[i] - 'a']; for(int j = 0; j < rlen; j++){ if(--A[ransomNote[j] - 'a'] < 0) return 0; } return 1; }};
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 马龙县| 平原县| 德州市| 博客| 图木舒克市| 高密市| 年辖:市辖区| 肥西县| 黄大仙区| 随州市| 营口市| 韶关市| 宁波市| 桓台县| 北川| 茂名市| 康定县| 潮安县| 绍兴市| 蒙山县| 正镶白旗| 兰考县| 保德县| 洪雅县| 抚远县| 西宁市| 滦南县| 阿拉善盟| 凤台县| 永靖县| 南开区| 都江堰市| 丰原市| 宣威市| 连云港市| 通海县| 昆明市| 聂拉木县| 潮安县| 石台县| 萨迦县|