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

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

LEETCODE--Ransom Note

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

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; }};
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 缙云县| 青冈县| 淳安县| 东乌| 增城市| 庐江县| 仪征市| 宜兴市| 成安县| 民权县| 阜南县| 和静县| 津南区| 盘山县| 广饶县| 玉林市| 台中市| 汾西县| 宁蒗| 海宁市| 乌拉特中旗| 丹东市| 清水河县| 黎川县| 武平县| 遵化市| 新丰县| 三河市| 浏阳市| 视频| 怀宁县| 普兰县| 大庆市| 德兴市| 林州市| 武宣县| 安福县| 湟源县| 象州县| 呼和浩特市| 武隆县|