• Java实现 LeetCode 438 找到字符串中所有字母异位词


    438. 找到字符串中所有字母异位词

    给定一个字符串 s 和一个非空字符串 p,找到 s 中所有是 p 的字母异位词的子串,返回这些子串的起始索引。

    字符串只包含小写英文字母,并且字符串 s 和 p 的长度都不超过 20100。

    说明:

    字母异位词指字母相同,但排列不同的字符串。
    不考虑答案输出的顺序。
    示例 1:

    输入:
    s: “cbaebabacd” p: “abc”

    输出:
    [0, 6]

    解释:
    起始索引等于 0 的子串是 “cba”, 它是 “abc” 的字母异位词。
    起始索引等于 6 的子串是 “bac”, 它是 “abc” 的字母异位词。
    示例 2:

    输入:
    s: “abab” p: “ab”

    输出:
    [0, 1, 2]

    解释:
    起始索引等于 0 的子串是 “ab”, 它是 “ab” 的字母异位词。
    起始索引等于 1 的子串是 “ba”, 它是 “ab” 的字母异位词。
    起始索引等于 2 的子串是 “ab”, 它是 “ab” 的字母异位词。

    class Solution {
     
        public List<Integer> findAnagrams(String s, String p) {
            List<Integer> res = new ArrayList<>();
            if (p.length() > s.length())
                return res;
    
            int[] pLetterCounts = new int[26];
            int[] sLetterCounts = new int[26];
            for (int i = 0; i < p.length(); ++i) {
                pLetterCounts[p.charAt(i) - 'a']++;
                sLetterCounts[s.charAt(i) - 'a']++;
            }
    
            for (int endIdx = p.length() - 1; endIdx < s.length(); ++endIdx) {
                int startIdx = endIdx - p.length() + 1;
                boolean isAnagrams = true;
                for (int i = 0; i < 26; ++i) {
                    if (sLetterCounts[i] != pLetterCounts[i]) {
                        isAnagrams = false;
                        break;
                    }
                }
    
                if (isAnagrams)
                    res.add(startIdx);
    
                if (endIdx != s.length() - 1){
                    sLetterCounts[s.charAt(startIdx) - 'a']--;
                    sLetterCounts[s.charAt(endIdx + 1) - 'a']++;
                }
    
            }
    
            return res;
        }
    }
    
  • 相关阅读:
    babel
    >/dev/null
    write to file
    fortran 77 example
    mix c with fortran
    automake
    Rockie's Android Porting Guide(4)——Add SD card to your system
    android平台初步分析
    Rockie's Android Porting Guide(4)——Add SD card to your system
    Android(1.5) 开机图片/文字/动画 修改
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13075683.html
Copyright © 2020-2023  润新知