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
  • 相关阅读:
    四则运算出题系统,java
    Javaweb测试
    《构建之法》 读书笔记(6)
    使用ProcDump在程序没有响应时自动收集dump
    NASA关于如何写出安全代码的10条军规
    C#和C++中的float类型
    避免在C#中使用析构函数Finalizer
    C#性能优化的一些技巧
    从bug中学习怎么写代码
    Code Smell那么多,应该先改哪一个?
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4809024.html
Copyright © 2011-2022 走看看