zoukankan      html  css  js  c++  java
  • Valid Anagram 解答

    Question

    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.

    (An anagram is a type of word play, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once; for example Torchwood can be rearranged into Doctor Who.)

    Solution

    Use hashmap to count each character's appearance time. Time complexity O(n), space cost O(n).

    Note here, counts.put(tmp, count.get(tmp)--); is wrong!

     1 public class Solution {
     2     public boolean isAnagram(String s, String t) {
     3         if (s == null || t == null)
     4             return false;
     5         if (s.length() != t.length())
     6             return false;
     7         Map<Character, Integer> counts = new HashMap<Character, Integer>();
     8         int length = s.length();
     9         for (int i = 0; i < length; i++) {
    10             char tmp = s.charAt(i);
    11             if (counts.containsKey(tmp)) {
    12                 int count = (int)counts.get(tmp);
    13                 counts.put(tmp, count + 1);
    14             } else {
    15                 counts.put(tmp, 1);
    16             }
    17         }
    18         for (int i = 0; i < length; i++) {
    19             char tmp = t.charAt(i);
    20             if (counts.containsKey(tmp)) {
    21                 int count = (int)counts.get(tmp);
    22                 if (count <= 0)
    23                     return false;
    24                 else
    25                     counts.put(tmp, count - 1);
    26             } else {
    27                 return false;
    28             }
    29         }
    30         return true;
    31     }
    32 }

    ++x is called preincrement while x++ is called postincrement.

    1 int x = 5, y = 5;
    2 
    3 System.out.println(++x); // outputs 6
    4 System.out.println(x); // outputs 6
    5 
    6 System.out.println(y++); // outputs 5
    7 System.out.println(y); // outputs 6
  • 相关阅读:
    c#两级菜单menu的动态实现
    单引号写入数据库,并结合写成函数和动静态类中方法对比小结
    google地图路径查询
    c# 图像旋转
    google地图简单
    asp.net gridview 添加属性
    linq to entity Oracle 执行存储过程或函数
    c# 判断非法字符
    c# 写入文件
    google map Inspecting DirectionsResults
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4809024.html
Copyright © 2011-2022 走看看