剑指offer 专项突破版 15、字符串中的所有变位词

题目链接

思路
  • 主要思路和上道题目一样,唯一需要注意的就是只需要一个数组就可以了,因为我们在找到变位词后数组元素会全变为0,当我们的指针整体右移后,数组的内容会回到最初用变位词初始化后,所以一个数组即可
    public class Solution {
    
        boolean isContains(int[] nums) {
            for (int num : nums) {
                if (0 != num)
                    return false;
            }
            return true;
        }
    
        public List<Integer> findAnagrams(String s, String p) {
            List<Integer> result = new ArrayList<>();
            int[] nums = new int[26];
    
            if (s.length() < p.length())
                return result;
            for (int i = 0; i < p.length(); i++) {
                nums[s.charAt(i) - 'a']++;
                nums[p.charAt(i) - 'a']--;
            }
    
            if (isContains(nums)) {
                result.add(0);
            }
    
            for (int i = p.length(); i < s.length(); i++) {
                nums[s.charAt(i) - 'a']++;
                nums[s.charAt(i - p.length()) - 'a']--;
                if (isContains(nums)) {
                    result.add(i - p.length() + 1);
                }
            }
    
            return result;
        }
    }
    
Go代码
func findAnagrams(s string, p string) (result []int) {
	if len(s) < len(p) {
		return
	}
	nums := make([]int, 26)

	for i := 0; i < len(p); i++ {
		nums[p[i]-'a']--
		nums[s[i]-'a']++
	}
	if contains(nums) {
		result = append(result, 0)
	}
	offset := len(p)
	for i := len(p); i < len(s); i++ {
		oldCh, newCh := s[i-offset], s[i]
		nums[oldCh-'a']--
		nums[newCh-'a']++
		if contains(nums) {
			result = append(result, i-offset+1)
		}
	}
	return

}

func contains(nums []int) bool {
	for i := 0; i < len(nums); i++ {
		if 0 != nums[i] {
			return false
		}
	}
	return true
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值