国产探花免费观看_亚洲丰满少妇自慰呻吟_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; }};
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 安远县| 定结县| 鄢陵县| 商河县| 甘南县| 商都县| 寻甸| 公安县| 额济纳旗| 西贡区| 万源市| 威海市| 巩留县| 玉龙| 方山县| 伊春市| 安国市| 改则县| 菏泽市| 阳城县| 湖南省| 浦城县| 且末县| 郯城县| 金昌市| 沅江市| 互助| 阳信县| 敦煌市| 丰城市| 万年县| 平远县| 双江| 南溪县| 汶川县| 宁乡县| 雷波县| 夏河县| 八宿县| 武宁县| 招远市|