LeetCode: 890. Find and Replace Pattern

题目: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());
	}
}

猜你喜欢

转载自blog.csdn.net/majinliang1234/article/details/82592300