zoukankan      html  css  js  c++  java
  • 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 string contains only lowercase alphabets.

    描述:Anagram是指对单词中的字母重新排列形成新的单词(详见wikipediahttps://en.wikipedia.org/wiki/Anagram)。给出两个字符串,判断两者是否相似。主要看两个字符串是否长度相等,是否出现的是同样字符,并且相同字符出现次数相同。

    解决:首先判断两个字符是否为空;长度是否相同;长度是否为0;然后用java中HashMap数据结构,首先遍历字符串s,纪录出现过的字符和字符出现的次数,然后遍历字符串t,若出现了s中没有出现过的字符,则直接返回false;若目前字符是在s中出现过的,则只需将map中纪录的value值-1,最后有value不为1者,返回false否则返回true。

    Answer:

     public  boolean isAnagram(String s, String t) {
             if(s==null && t==null)
                 return true;
             if(s.length() != t.length())
                 return false;
             if(s.length()==0 && t.length()==0)
                 return true;
             
             HashMap<Character, Integer> map = new HashMap<Character, Integer>();
             for(int i=0; i<s.length(); i++){
                      if(!map.containsKey(s.charAt(i))){
                          map.put(s.charAt(i), 1);
                      } else {
                          int v = map.get(s.charAt(i));
                          map.put(s.charAt(i), v+1);
                      }     
             }
             
             for(int i=0; i<t.length(); i++){
                      if(!map.containsKey(t.charAt(i)))
                          return false;
                      else {
                          int v = map.get(t.charAt(i));
                          map.put(t.charAt(i), v-1);
                      }
             }
             
             Iterator iter = map.entrySet().iterator();
             while(iter.hasNext()){
                     Map.Entry entry = (Map.Entry) iter.next();
                     if((int) entry.getValue() != 0)
                         return false;
             }
             
             return true;
             
         }
        
  • 相关阅读:
    SAP BI 常用TCODE
    ABAP Table Control
    Smartforms 设置纸张打印格式
    SAP库存历史库存表更新逻辑 (转)
    ABAP 调用远程rfc
    php 随机生成数字字母组合
    php错误提示 open_basedir restriction in effect 解决
    MySQL Errno : 1062 错误修复
    mysql数据库允许远程连接
    httpd.conf文件与.htaccess文件的对比
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/4782885.html
Copyright © 2011-2022 走看看