LeetCode Valid Anagram

【智能机器人开发全流程:硬件选型、软件架构与ROS实战,打造高效机器人系统】 通过模块化设计与ROS框架的灵活扩展,可快速搭建适应不同场景的机器人系统。实际开发中需重点关注。 阅读详情

原题链接在这里:https://leetcode.com/problems/valid-anagram/

这道题可以用HashMap来解决,首先判断 s 和 t 长度是否相等,若不等返回 false。

若想等,对于s的每一个character存入hm,value是该character出现的次数。

然后遍历t的每一个character,从hm中相应减出去,若在减除过程中碰到hm中没有的character,直接返回false。

若没有遇到hm中没有的character,剪完后看hm的value是不是都是0,都是0,两个string才是anagram。


Note: 1. hm.get(key)  返回的是一个数,不可以直接写成 hm.get(key)++,  这里error-prone。还有加时候用s,减时候用t,很容易搞  混。

  2. When iterating HashMap, 要注意先写Set,再用这个 Set的iterator() function。 还有写key的type注意要写成Object,不可以  写成char或者Character,否则会报错,如下:

Set keySet = hm.keySet();
Iterator it = keySet.iterator();
while(it.hasNext()){
    Object key = it.next();
    System.out.println(hm.get(key));
}

  3. 若是要print HashMap, 可用以下方法:

for(Character key : hm.keySet()){
    System.out.println("Key: " + key + " Value: " + hm.get(key));
}


补充:回头一看,这道题可以直接sort 两个string 然后比较,相同就返回true。 Code 在 Method 2 中。

不过要注意,for Strings, equals() method works as str1.equals(str2); for Arrays, equals() method works as Arrays.equals(arr1, arr2).

AC Java:

Method 1:

public class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length() != t.length()){
            return false;
        }
        
        //Creat HashMap with character as key and number of this character as value
        HashMap<Character, Integer> hm = new HashMap<>();
        for(int i = 0; i < s.length(); i++){
            if(hm.containsKey(s.charAt(i))){
                int temp = hm.get(s.charAt(i))+1; //error 1
                hm.put(s.charAt(i), temp);
            }else{
                hm.put(s.charAt(i), new Integer(1));
            }
        }
        
        //Delete corresponding keys from HashMap
        for(int i = 0; i< t.length(); i++){
            if(hm.containsKey(t.charAt(i))){
                int temp = hm.get(t.charAt(i))-1;
                hm.put(t.charAt(i), temp);
            }else{
                return false;
            }
        }
        
        //Check if the value is 0
        Set keySet = hm.keySet();
        Iterator it = keySet.iterator();
        while(it.hasNext()){
            Object key = it.next(); //error 2
            if(hm.get(key) != 0){
                return false;
            }
        }
        
        return true;
    }
}


Method 2:

public class Solution {
    public boolean isAnagram(String s, String t) {
         //Method 2
        char[] temp1 = s.toCharArray();
        char[] temp2 = t.toCharArray();
        Arrays.sort(temp1);
        Arrays.sort(temp2);
        
        return Arrays.equals(temp1,temp2);
    }
}



做了一个3DTiles编辑器,支持3DTiles的预览和裁剪导出 3DTiles编辑器的功能极其简洁,核心就是3DTiles格式模型的预览和裁剪。为了演示方便,本文所使用的源数据为mipmap3d[1]网站所提供的无人机拍摄影像,并进行3DTiles构建。打开软件,输入的绝对路径之后,点击添加模型,就可以将模型加载进预览区。之后,点击裁剪模式按钮,默认会出现立方体裁剪框,可通过拖动句柄的方式去调整裁剪框的范围。同时,除了默认的盒体裁切模式外,还支持多边形裁切,点击多边形裁切后,可切换到顶视图,选择重绘多边形,可进行打点绘制。 阅读详情

相关推荐

OpenBCI脑电帽硬件DIY与低成本搭建实战

本文详细介绍了如何通过第三方兼容硬件和开源设计,低成本DIY一套功能完备的OpenBCI脑电采集系统。从硬件选购、组装、软件配置到信号调试,提供了完整的实战指南,将总成本控制在千元级别,使脑机接口技术对爱好者、学生和研究者变得更加触手可及。

weixin_29322855的博客 785

LeetCode第98题(验证二叉搜索树)

原题如下: 给定一个二叉树,判断其是否是一个有效的二叉搜索树。 假设一个二叉搜索树具有如下特征: 节点的左子树只包含小于当前节点的数。 节点的右子树只包含大于当前节点的数。 所有左子树和右子树自身必须也是二叉搜索树。 示例 1: 输入: 2 / 1 3 输出: true 示例 2: 输入: 5 / 1 4 / 3 6 输出: false 解释: 输入为: [5,1,4,null,...

qq_42203013的博客 1031

Qt实战:用QTreeView+QStandardItemModel实现多级多列文件浏览器(附完整代码)

本文深入探讨了使用Qt的QTreeView与QStandardItemModel构建多级多列文件浏览器的完整实践。通过分析模型/视图框架的优势,详细演示了从基础框架搭建、模拟数据填充,到对接真实文件系统实现懒加载的全过程。文章还涵盖了自定义委托、多列排序、右键菜单等高级定制技巧,并提供了性能优化建议和完整的代码示例,帮助开发者打造功能强大且高效的工业级文件管理界面。

weixin_29021291的博客 423

leetcode 98. 验证二叉搜索树

给定一个二叉树,判断其是否是一个有效的二叉搜索树。一个二叉搜索树有如下定义:左子树只包含小于当前节点的数。右子树只包含大于当前节点的数。所有子树自身必须也是二叉搜索树。示例 1: 2 / \ 1 3 二叉树[2,1,3], 返回 true.示例 2: 1 / \ 2 3 二叉树 [1,2,3], 返回 false.啊我有点蠢了。。中序遍历做/** * De...

1988的博客 1585

SystemVerilog新手实战指南:iverilog与VScode的完美组合

本文为SystemVerilog新手提供了一套高效入门方案,详细介绍了如何利用开源编译器iverilog与轻量编辑器VScode搭建学习环境。内容涵盖十分钟快速安装配置、首个工程从编码到查看波形的完整流程,并演示了动态数组和队列等SystemVerilog新特性的使用,旨在帮助初学者避开复杂商业工具,快速掌握数字电路设计与验证的核心技能。

f6g7h8i9j的博客 513

【MODIS处理工具】MRT(MODIS Reprojection Tool) 下载及安装

【MODIS处理工具】MRT(MODIS Reprojection Tool) 下载及安装

WW、forever的博客 2405

lintcode(95)验证二叉查找树

描述: 给定一个二叉树,判断它是否是合法的二叉查找树(BST) 一棵BST定义为: 节点的左子树中的值要严格小于该节点的值。节点的右子树中的值要严格大于该节点的值。左右子树也必须是二叉查找树。一个节点的树也是二叉查找树。 样例: 一个例子: 2 / \ 1 4 / \ 3 5 上述这棵二叉树序列化为 {2,1,4,#,#,3,

sunday0904的博客 2135

最优控制 (Optimal Control) 算法详解及案例分析

最优控制是一种通过优化控制输入,使系统在满足约束条件的情况下达到最优性能的控制方法。其目标是最小化或最大化一个性能指标。

闲人编程的博客 2090

LeetCode 242. Valid Anagram 题解

本题是字符串处理的基础问题。排序比较字符计数边界条件处理通过本题可以深入理解字符串处理的基本方法。

cannonjinx的博客 4413

69页完整版智慧港口综合解决方案

智慧港口需求4港机远程操控等自动化改造需求自动化码头AGV无线通信及专用视频系统需求安全生产视频监控类需求港机RCMS及设备管理需求岸边智能理货码头三维全景应用智慧港口解决方案5自动化码头AGV/跨运车/无人集卡无线接入港机远控视觉及冗余无线通信视觉集卡防吊起系统集装箱码头岸边智能理货港机RCMS系统无线接入港机智能化管理(无线高清视频监控、一键报警、远程抄表系统)港口拖轮无线接入岸边溢油监测系统TD-LTE覆盖及业务终端接入港口生产管理系统港口可视化集群调度港口GiNMS综合网络设备智能管理全球作业效率最

zuoan1993的博客 2128

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

Leetcode 242 Valid Anagram

Leetcode 242 Valid Anagram#include <string> #include <algorithm> #include <vector> using namespace std;class Solution { public: bool isAnagram(string s, string t)//too slow { sort(s.begin(),

自己的学习笔记 419

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Leetcode 242. Valid Anagram (python+cpp)

Leetcode 242. Valid Anagram题目解析: 题目 解析: python: class Solution: def isAnagram(self, s: str, t: str) -> bool: if len(s) != len(t): return False counts = collections.defaultdict(int) for i in rang

qq_37821701的博客 246

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

leetcode 242. Valid Anagram

Python leetcode 242. Valid Anagram 242. 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"

accumulate_zhang的博客 430

LeetCode 242. Valid Anagram 题解(C++)

Given two strings s and t, write a function to determine if t is an anagram of s.

prayyojay的博客 1663

[leetcode]242. Valid Anagram

[leetcode]242. Valid Anagram Analysis 厉害的人总是那么的厉害呀~—— [菜鸡反省中~] Given two strings s and t , write a function to determine if t is an anagram of s. 简单来说就是判断两个字符串中的字符是否都一样,很简单,直接把所有字符排一下序,然后遍历...

weixin_32135877的博客 149

[LeetCode]242. Valid Anagram

[LeetCode]242. Valid Anagram题目描述思路1 hash map 对s中计数加,对t中计数减,结果不为0或者不存在的直接返回false 2 sort 直接排序后 返回 s == t ,效率最低 3 array, 初始化一个长度为26,值为0的数组,对字符串同时遍历,最后检查数组元素,有不为0的元素直接返回false代码#include<iostream> #includ

Lcharon的博客 431

leetcode刷题记录-242. Valid Anagram

leetcode刷题记录-242. Valid Anagram 1.题目要求   Given two strings s and t, write a function to determine if t is an anagram of s.   Note:   You may assume the string contains only lowercase alphabets.  ...

zhaizhan501的博客 265

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.Note: You may assume the s

追风筝的吃货,汪~ 683

LeetCode 242 Valid Anagram

LeetCode 242 Valid Anagram Problem Description: 给出两串字符串,判断第二串字符串是否由第一串字符串乱序得到的。 具体的题目信息: https://leetcode.com/problems/valid-anagram/description/ Example: Solution:(挺精致的答案) class Solution { ...

萤火虫啊飞呀飞 202

week8-leetcode #242-Valid Anagram

week8-leetcode #242-Valid Anagram题目地址: https://leetcode.com/problems/valid-anagram/description/QuestionGiven two strings s and t, write a function to determine if t is an anagram of s.ExampleFor exampl

perdon123123的博客 180

[LeetCode]242. Valid Anagram 解题报告(C++)

[LeetCode]242. Valid Anagram 解题报告(C++) 题目描述 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 Exam...

【黑键】 233

【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
上一篇: LeetCode Count Primes
下一篇: Java: Difference between ArrayList and LinkedList
Dylan_Java_NYC
博客等级 码龄11年 1粉丝 134原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值