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

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

LEETCODE--Ransom Note

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

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; }};
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 恩施市| 嘉峪关市| 通山县| 嘉黎县| 威信县| 吉首市| 黑山县| 京山县| 宁河县| 广昌县| 武陟县| 濮阳县| 奈曼旗| 开化县| 余江县| 五大连池市| 黑河市| 衡阳市| 延边| 澄城县| 曲阜市| 宜章县| 普格县| 乳源| 太仆寺旗| 木兰县| 南宫市| 普洱| 喀喇| 团风县| 和龙市| 临安市| 泗阳县| 久治县| 顺昌县| 东莞市| 怀来县| 海林市| 黑龙江省| 长泰县| 莱芜市|