zoukankan      html  css  js  c++  java
  • [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.

    题意及分析:要求判断两个字符串是否由相同的字符组成。这里有两种方法,(1)统计每个不同的字符在字符串中出现的次数,然后判断   (2)将字符串按照相同的顺序排序,然后判断两个字符串的每个位置的字符是否相等。

    代码1:

    public class Solution {
        public boolean isAnagram(String s, String t) {
            if(t.length()!=s.length()) return false;
    
    		int[] count=new int[26];  //因为都是小写字母,所以最多26个字符
    		
    		for(int i=0;i<s.length();i++){
    			count[s.charAt(i)-'a']++;
    			count[t.charAt(i)-'a']--;
    		}
    		
    		for(int i=0;i<count.length;i++){
    			if(count[i]!=0) return false;
    		}
    		return true;
        }
    }

    代码2:

    public class Solution {
        public boolean isAnagram(String s, String t) {
            if(t.length()!=s.length()) return false;
            char[] s1=s.toCharArray();
            char[] t1=t.toCharArray();
    		
    		Arrays.sort(s1);
    		Arrays.sort(t1);
    		
    		for(int i=0;i<s.length();i++){
    			if(s1[i]!=t1[i]) return false;
    		}
    		return true;
        }
    }
    

      

  • 相关阅读:
    jvm的代码缓存耗尽导致性能下降
    几次印象深刻的网上事故
    是时候对十二年的工作回顾了!
    基于GitLab的前端Assets发布体系
    元数据简介
    JSON和JSONP
    Javascript模块规范
    Javascript编程风格
    Require JS
    JavaScript的AMD规范
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7101757.html
Copyright © 2011-2022 走看看