zoukankan      html  css  js  c++  java
  • 【09_242】Valid Anagram

    Valid Anagram

    My Submissions
    Total Accepted: 43694 Total Submissions: 111615 Difficulty: Easy

    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.

    Follow up:
    What if the inputs contain unicode characters? How would you adapt your solution to such case?

    这个方法可以把包括unicode characters在内的都进行对比。

    对string的内部进行排序,这个方法要记住!

    这个方法的头函数是#include <algorithm>

    C++写法:

     1 class Solution {
     2 public:
     3     bool isAnagram(string s, string t) {
     4         sort(s.begin(), s.end());
     5         sort(t.begin(), t.end());
     6         if (s == t)
     7            return true;
     8         else 
     9            return false;
    10     }
    11 };

    我的解法时间太长,下面是Discuss里面的几种简单解法:

    1. The idea is simple. It creates a size 26 int arrays as buckets for each letter in alphabet. It increments the bucket value with String s and decrement with string t. So if they are anagrams, all buckets should remain with initial value which is zero. So just checking that and return
    1 public class Solution {
    2     public boolean isAnagram(String s, String t) {
    3         int[] alphabet = new int[26];
    4         for (int i = 0; i < s.length(); i++) alphabet[s.charAt(i) - 'a']++;
    5         for (int i = 0; i < t.length(); i++) alphabet[t.charAt(i) - 'a']--;
    6         for (int i : alphabet) if (i != 0) return false;
    7         return true;
    8     }
    9 }

      

    看了别的解答发现,核心思想都一样,但是语句表达上各有千秋,有的很简单比如上面的要学习。

  • 相关阅读:
    sql批量生成showdocs数据字典的md文档
    kis注册账套的时候选不到数据
    kis中导入其它账套的科目
    sql server查询某个字段的类型
    sql server修改默认值语句
    k3 cloud查询关联关系
    k3 cloud中根据表明查找业务对象
    计算机系统要素(存储器)
    计算机系统要素(多路复用器)
    领域设计:聚合与聚合根
  • 原文地址:https://www.cnblogs.com/QingHuan/p/5046544.html
Copyright © 2011-2022 走看看