LeetCode算法题-Valid Anagram(Java实现)

Palabos 并行计算与多物理场模拟实战指南 本文详细介绍了Palabos在并行计算与多物理场模拟中的实战应用。作为基于C++和LBM的开源CFD工具,Palabos通过MPI实现高效并行计算,特别适合处理复杂流体模拟问题。文章涵盖从基础安装、多物理场耦合技巧到性能优化策略,并分享工业级应用案例与调试经验,帮助开发者快速掌握这一强大工具。 阅读详情

这是悦乐书的第198次更新,第205篇原创

01 看题和准备

今天介绍的是LeetCode算法题中Easy级别的第61题(顺位题号是242)。给定两个字符串s和t,写一个函数来确定t是否是s的anagram。例如:

输入:s =“anagram”,t =“nagaram”

输出:true

输入:s =“rat”,t =“car”

输出:false

注意:您可以假设该字符串仅包含小写字母。

跟进:如果输入包含unicode字符怎么办? 您如何使您的解决方案适应这种情况?


本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Java语言编写和测试。

02 第一种解法

关于题目中anagram的意思,结合给出的两个示例,大意就是两字符串使用的小写字母一样,但是每个字母所处的位置不是全都一样。此解法是将两字符串s、t转换为字符数组,然后将数组排序,最后比较两数组的元素是否相等,这里借助了工具类Arrays。

此解法的时间复杂度是O(nlog(n)),空间复杂度是O(n)。

public boolean isAnagram(String s, String t) {
    if (s == null || t == null || s.length() != t.length()) {
        return false;
    }
    char[] ch = s.toCharArray();
    char[] ch2 = t.toCharArray();
    Arrays.sort(ch);
    Arrays.sort(ch2);
    return Arrays.equals(ch, ch2);
}

03 第二种解法

题目限制了只有英文小写字母,我们可以定义一个长度只有26的整数数组,对字符串进行遍历,以当前字符减去字符a所表示的整数为索引,找到对应元素,字符串s所在的字符进行自增,字符串t所在的字符进行自减,然后判断数组中的元素,只要任一元素不等于0,则说明s和t不满足anagram的条件。

此解法时间复杂度是O(n),空间复杂度是O(1)。

public boolean isAnagram2(String s, String t) {
    if (s == null || t == null || s.length() != t.length()) {
        return false;
    }
    int[] arr = new int[26];
    for (int i=0; i<s.length(); i++) {
        arr[s.charAt(i)-'a']++;
        arr[t.charAt(i)-'a']--;
    }
    for(int num : arr) {
        if (num != 0) {
            return false;
        }
    }
    return true;
}

04 第三种解法

使用HashMap,key为字符串的单个字符,value为此字符出现的次数,这里借助HashMap的getOrDefault方法来实现,如果存在该key,返回对应的value,否则返回默认值。

先将字符串s的每个字符存入HashMap中,然后遍历字符串字符串t,依次获取每一个字符,如果当前字符不在HashMap中存在,直接返回false,然后将字符存进HashMap中,value值减1,如果当前字符的出现次数为0了,将其remove掉,最后判断HashMap是否为空。

此解法因为用到了map.containsKey()方法,所以时间复杂度最好的情况是O(n),最坏的情况是O(n^2),空间复杂度是O(n)。

public boolean isAnagram3(String s, String t) {
    if (s == null || t == null || s.length() != t.length()) {
        return false;
    }
    HashMap<Character,Integer> map = new HashMap<Character,Integer>();
    for (int i=0; i<s.length(); i++) {
        char ch = s.charAt(i);
        map.put(ch, map.getOrDefault(ch, 0)+1);
    }
    for (int j=0; j<t.length(); j++) {
        char ch = t.charAt(j);
        if (!map.containsKey(ch)) {
            return false;
        }
        map.put(ch, map.get(ch)-1);
        if (map.get(ch) == 0) {
            map.remove(ch);
        }
    }
    return map.isEmpty();
}

此解法是可以应对那些带有unicode字符的字符串,当然也可以使用像第二种解法的那样,使用数组,但是数组容量要扩大到256,其他的思路都是一样的。

05 小结

算法专题目前已连续日更超过一个月,算法题文章61+篇,公众号对话框回复【数据结构与算法】、【算法】、【数据结构】中的任一关键词,获取系列文章合集。

以上就是全部内容,如果大家有什么好的解法思路、建议或者其他问题,可以下方留言交流,点赞、留言、转发就是对我最大的回报和支持!

huggingface 镜像站推荐 在做 Ai 应用开发或者学习的时候,我们经常需要下载各种模型,而 huggingface 的模型下载速度很慢或者根本就连不上,这里推荐一个 huggingface 的镜像站,速度很快,可以大大提高我们的效率。 阅读详情

相关推荐

操作系统期末大题类型题解

额,OS主要这回考程序分析题,PV操作、生产者消费者啊,哲学家进餐问题,死锁问题啊,如何避免死锁,经典银行家算法,页面置换算法啥的,磁盘调度......总计还有很多,就不一一说了 PV操作 谈到PV操作,首先要了解什么是信号量,其实就是用来解决互斥与同步问题的,分为原语wait(S)和signal(S),也就是我们常说的PV操作,在这里给出王道上的概念 wait(S){ while(S>0) S=S-1; } signal(S){ S=S+1; } 记录型信号量

ZXxxiaoxuan的博客 796

[LeetCode] Anagram

Given an array of strings, return all groups of strings that are anagrams. Note: All inputs will be in lower-case. 思路:用一个map保存字符串,如果字符串第一次遇到,那么把这个字符串放入map,如果第2、3、4、...次遇到,那么把第1、2、3、4、...次的字符串放入返回的向量中

jiyanfeng1的专栏 821

HFSS与AI融合:智能算法如何重塑天线设计流程

本文探讨了HFSS与AI融合如何通过智能算法革新天线设计流程。在5G/6G通信时代,AI技术如机器学习和遗传算法显著提升了高频电磁场仿真效率,将传统设计周期从数周缩短至数小时,并优化了天线性能。文章详细介绍了AI与HFSS的集成策略、关键技术突破及典型应用案例,展示了智能算法在天线设计中的巨大潜力。

weixin_29035147的博客 781

哈希笔记(六)map/数组

(383)赎金信 解法一:利用map实现,完全是自己写的 class Solution { public: bool canConstruct(string ransomNote, string magazine) { unordered_map<char, int> result_map; for (int i=0; i < ransomNote.length(); i++){ result_map[ransomNot

weixin_51249243的博客 199

示波器面板上的隐藏功能:如何利用BW Limit和EXT TRIG提升测量精度

本文深入探讨示波器面板上的隐藏功能BW Limit和EXT TRIG,揭示它们如何提升测量精度。通过带宽限制(BW Limit)有效滤除高频噪声,结合外部触发(EXT TRIG)确保稳定信号捕获,为电子测量提供专业解决方案。特别适用于开关电源、传感器信号等复杂场景的高精度测量需求。

weixin_30300225的博客 519

CSM中一些常见问题的解决方式

CSM中一些常见问题的解决方式 抖动 摄像机在每帧移动或者旋转时,会产生较严重的抖动问题。

小龙虾的博客 2133

【LeetCode】字符串系列(Anagram)

49. Group Anagrams 题目:将输入字符串组按组成分类,输出分类好的字符串组 思路:HashMap——设置HashMap,Key为每类字符串按升序排列,Value为该类所有字符串(List)。对于输入的每个字符串,进行字符数组转换,再进行排序,然后转换回字符串,如果HashMap中不包含该类字符串,就建新key,否则将该值加入Value。public class Solution

liyinan11的博客 497

MTK Android 12 Clone Project 克隆项目

本文介绍了如何使用MTK Android 12 Clone Project 克隆一个新的项目。通过使用绝对路径执行Perl脚本,并根据需要选择升级或降级位数,可以成功地生成一个新的项目并进行编译。希望本文对xdm有所帮助。

我其实什么都不会 943

LeetCode:242 Valid Anagram Java

Given two strings s and t, write a function to determine if t is an anagram of s.For example, s = “anagram”, t = “nagaram”, return true. s = “rat”, t = “car”, return false.Note: You may assume the s

Json随笔 1935

RoCEv2 (RDMA over Converged Ethernet) 技术详细介绍

本文深入解析RDMA over Converged Ethernet (RoCEv2)技术,该技术是AI时代算力网络的核心。文章从四个维度展开:首先阐述RDMA如何通过零拷贝和内核旁路解决传统网络的数据搬运瓶颈;接着拆解RoCEv2协议栈,对比其与InfiniBand和iWARP的特性差异;然后分析其在分布式AI训练、高性能存储等场景的关键价值;最后提供实战指南,强调无损网络配置、流量隔离和精细监控的重要性。RoCEv2虽能带来微秒级延迟和极低CPU开销,但需精心设计网络环境才能发挥最大效能。

技术引领业务创新 1393

Cadence PSpice 仿真0:绘制电路图方法图文教程

在使用PSpice进行电路的仿真时,首先需要使用带有PSpice模型的元器件来绘制电路图,本文简单介绍进行电路图绘制是常用的几种需要掌握的方法,以满足PSpice仿真绘制简单电路图所用。

fydar的博客 4710

【LeetCode OJ 242】Valid Anagram

题目链接:https://leetcode.com/problems/valid-anagram/ 题目:Given two strings s and t, write a function to determine if t is an anagram of s. For example, s = "anagram", t = "nagaram", return true

1391

2018安徽省青少年信息学奥林匹克(AHOI)初中组

12 种合法的排列分别为:1, 3, 2, 4, 2, 3, 1, 4, 3, 1, 4, 2, 3, 2, 4, 1, 1, 3, 4, 2, 2, 3,4,1,1,4,2,3, 2,4,1,3, 4,1,3,2, 4,2,3,1, 1,4,3,2, 2,4,3,1。分为 2 组,一组的队员实力值是{4, 5, 2, 3},一组是{-4, -3, -5},其中最小的组人数为 3,可以发现没有比 3 更优的分法了。[0, 1, 1, 2]同样不是合法的分组方案,因为出现了两个实力值为 1 的选手。

weixin_42358969的博客 1143

【本人秃顶程序员】刷题啦:LeetCode算法题-Valid Anagram

←←←←←←←←←←←← 我都秃顶了,还不点关注! 今天介绍的是LeetCode算法题中Easy级别的题。给定两个字符串s和t,写一个函数来确定t是否是s的anagram。例如: 输入:s =“anagram”,t =“nagaram” 输出:true 输入:s =“rat”,t =“car” 输出:false 注意: 您可以假设该字符串仅包含小写字母。 跟进: 如果输入包含unicode字符怎么...

本人秃顶程序员的博客 193

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

LeetCode Valid Anagram JAVA

Given two strings s and t, write a function to determine if t is an anagram of s. For example, s = "anagram", t = "nagaram", return true. s = "rat", t = "car", return false. Note: You may a

石楠花的博客 432

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

Java [Leetcode 242]Valid Anagram

题目描述: Given two stringssandt, write a function to determine iftis an anagram ofs. For example,s= "anagram",t= "nagaram", return true.s= "rat",t= "car", return false. 解题思路: 将字符串进行排...

dkk37351的博客 107

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

LeetCode 242 Valid Anagram题解

题目:https://leetcode.com/problems/valid-anagram/ 题目: Given two strings s and t, write a function to determine if t is an anagram of s. 给定两个字符串s和t,写出一个函数来判断t是否是s的变位词。 For example, s = "anag

赞美月亮的专栏 630

【Leetcode】Valid Anagram

题目链接:https://leetcode.com/problems/valid-anagram/ 题目: Given two strings s and t, write a function to determine if t is an anagram of s. For example, s = "anagram", t = "nagaram", return true

业精于勤,荒于嬉 2033

LeetCode Valid Anagram

题目: Given two strings s and t, write a function to determine if t is an anagram of s. For example, s = "anagram", t = "nagaram", return true. s = "rat", t = "car", return false. 中文翻译: 就是要找

渣渣 445

leetcode算法之Valid Anagram

原文算法说明如下: Given two strings s and t, write a function to determine if t is an anagram of s. For example, s = "anagram", t = "nagaram", return true. s = "rat", t = "car", return false. 翻译:

AI开源工具分享 994

leetcode-242.Valid Anagram

题目 Given two strings s and t , write a function to determine if t is an anagram of s. Example 1: Input: s = “anagram”, t = “nagaram” Output: true Example 2: Input: s = “rat”, t = “car” Output: false N...

不思量 240

Valid Anagram

Given two strings s and t, write a function to determine if t is an anagram of s. For example, s = "anagram", t = "nagaram", return true. s = "rat", t = "car", return false. Note: You may assum

chenyx90的博客 462

LeetCode-242. Valid Anagram [C++][Java]

Given two stringssandt, returntrueiftis an anagram ofs, andfalseotherwise. AnAnagramis a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

贫道绝缘子的博客 248

LeetCode——Valid Anagram

Description: Given two strings s and t, write a function to determine if t is an anagram of s. For example, s = "anagram", t = "nagaram", return true. s = "rat", t = "car", return false. Note: You ...

weixin_33816946的博客 75

leetcode之valid anagram

有两种解法,一种是将两个单词按照字母进行排序,在比较排序后的字符串是否相等。第二种解法是建立一个26字母的数组,统计两个字符串的各个字母的出现次数,若相同则一样。(1)C语言实现bool isAnagram(char* s, char* t) {    int count[26]={0};    //char c;    for(int i=0;i&lt;strlen(s);i++){      ...

代码草根的专栏 347

LeetCode 242. Valid Anagram

欢迎访问原文所在博客:https://52heartz.top/articles/leetcode-242-valid-anagram/ 解答1[Java]: class Solution { public boolean isAnagram(String s, String t) { if(s.length() != t.length()) return false; ...

user2639的博客 155
上一篇: LeetCode算法题-Delete Node in a Linked List(Java实现)
下一篇: LeetCode算法题-Binary Tree Paths(Java实现-3种解法)
程序员小川
博客等级 码龄10年 47粉丝 305原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值