LeetCode 1347. Minimum Number of Steps to Make Two Strings Anagram

本文详细解析了LeetCode第1347题,探讨如何通过最少步骤将字符串t转化为与s相同的字母异位词。通过计算两字符串中各字符的差异,提供两种高效解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[Med] LeetCode 1347. Minimum Number of Steps to Make Two Strings Anagram

链接: https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram/

题目描述:
Given two equal-size strings s and t. In one step you can choose any character of t and replace it with another character.
Return the minimum number of steps to make t an anagram of s.
An Anagram of a string is a string that contains the same characters with a different (or the same) ordering.

给你两个长度相等的字符串 s 和 t。每一个步骤中,你可以选择将 t 中的 任一字符 替换为 另一个字符。
返回使 t 成为 s 的字母异位词的最小步骤数。
字母异位词 指字母相同,但排列不同的字符串。

Example 1:

Input: s = “bab”, t = “aba”
Output: 1
Explanation: Replace the first ‘a’ in t with b, t = “bba” which is anagram of s.

Example 2:

Input: s = “leetcode”, t = “practice”
Output: 5
Explanation: Replace ‘p’, ‘r’, ‘a’, ‘i’ and ‘c’ from t with proper characters to make t anagram of s.

Example 3:

Input: s = “anagram”, t = “mangaar”
Output: 0
Explanation: “anagram” and “mangaar” are anagrams.

Example 4:

Input: s = “xxyyzz”, t = “xxyyzz”
Output: 0

Example 5:

Input: s = “friend”, t = “family”
Output: 4

Constraints:

  • 1 <= s.length <= 50000
  • s.length == t.length
  • s and t contain lower-case English letters only.

Tag: String
解题思路
检查从字符串A转到字符串B需要改变几个字母。首先保证了两个字符串长度相同。很简单,计算一下A中多了几个就可以了

解法一:

class Solution {
    public int minSteps(String s, String t) {
        int[] l1 = new int[26];
        int[] l2 = new int[26];
        for(int i=0; i<s.length(); i++){
            l1[s.charAt(i)-'a']++;
            l2[t.charAt(i)-'a']++;
        }
        
        for(int i=0; i<l1.length; i++){
            l1[i] -= l2[i];
        }
        int res =0;
        
        for(int i: l1) res+=i>0?i:0;
        return res;
    }
}

解法二:
可以进一步简化

class Solution {
    public int minSteps(String s, String t) {
        int[] list = new int[26];
       
        for(int i=0; i<s.length(); i++){
            list[s.charAt(i)-'a']++;
            list[t.charAt(i)-'a']--;
        }
        
        int res =0;
        
        for(int i: list) res+=i>0?i:0;
        
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值