Re: [閒聊] 每日LeetCode已回收

看板Marginalman作者 (みけねこ的鼻屎)時間2年前 (2023/01/01 14:55), 編輯推噓2(200)
留言2則, 2人參與, 2年前最新討論串171/719 (看更多)
290. Word Pattern 給你兩個陣列表示一個字元對應一個字串的關係,檢查左邊是否和右邊匹配。 Example: Input: pattern = "abba", s = "dog cat cat dog" Output: true Explain: a = dog b = cat Input: pattern = "abba", s = "dog cat cat fish" Output: false Exaplain: "a = dog = fish" is invalid 思路: 1.先把字串s拆分成單字並檢查長度是否等於pattern,若否直接返回false。 2.先遍歷pattern把pattern[i] -> s[i] 的關係保存到map,過程中如果發現pattern[i] 已經保存過了,則檢查s[i]是否等於pattern[i]的value值,若否直接返回false。 3.再遍歷一次map並用一個set檢查是否有重複的value值,若存在重複直接返回false。 4.最後返回true。 Java Code: ---------------------------------------------------------------------- class Solution { public boolean wordPattern(String pattern, String s) { String[] words = s.split(" "); if (words.length != pattern.length()) { return false; } Map<Character, String> map = new HashMap<>(); for (int i = 0; i < pattern.length(); i++) { char c = pattern.charAt(i); if (map.containsKey(c) && !map.get(c).equals(words[i])) { return false; } map.put(c, words[i]); } Set<String> set = new HashSet<>(); for (Map.Entry<Character, String> entry : map.entrySet()) { if (set.contains(entry.getValue())){ return false; } set.add(entry.getValue()); } return true; } } ---------------------------------------------------------------------- 今天一登入就跳出這個 https://i.imgur.com/13WC9Ra.png
-- https://i.imgur.com/PIoxddO.jpg
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.100.75.86 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1672556134.A.944.html

01/01 14:57, 2年前 , 1F
大師
01/01 14:57, 1F

01/01 14:59, 2年前 , 2F
大師 我直接想從2.開始 忘記有可能長度不一樣==
01/01 14:59, 2F
文章代碼(AID): #1ZiIvcb4 (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1ZiIvcb4 (Marginalman)