LeetCode: 890. Find and Replace Pattern
阿新 • • 發佈:2018-12-22
題目:890. Find and Replace Pattern(https://leetcode.com/problems/find-and-replace-pattern/description/)
解法:
將元素的出現的位置放入陣列中,當元素第一次出現時,他在陣列中的值是預設值0,當相同的再次元素出現時,它在陣列中的值應該相同,否則說明不匹配。
class Solution { public List<String> findAndReplacePattern(String[] words, String pattern) { return Arrays.stream(words) .filter(word -> { boolean match = true; int[] p = new int[26], s = new int[26]; for (int i = 0; i < word.length(); i++) { // when char first appear, it will read as 0 from p or s if (s[word.charAt(i) - 'a'] != p[pattern.charAt(i) - 'a']) { match = false; break; } else { s[word.charAt(i) - 'a'] = i + 1; // plus one to avoid 0 in p and s, because the element in p and s default is 0 p[pattern.charAt(i) - 'a'] = i + 1; } } return match; }) .collect(Collectors.toList()); } }