zoukankan      html  css  js  c++  java
  • LeetCode 242. Valid Anagram

    原题链接在这里:https://leetcode.com/problems/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.

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

    题解:

    维护一个map, s对应char位++, t对应char位--. 若是map有非零位便return false.

    Time Complexity: O(n), n 为string长度.

    Space: O(1). 用了一个array当map.

    AC Java:

    Method 1:

     1 public class Solution {
     2     public boolean isAnagram(String s, String t) {
     3         if(s == null && t == null){
     4             return true;
     5         }
     6         if(s == null || t == null){
     7             return false;
     8         }
     9         if(s.length() != t.length()){
    10             return false;
    11         }
    12         
    13         int [] map = new int[256];
    14         for(int i = 0; i<s.length(); i++){
    15             map[s.charAt(i)]++;
    16         }
    17         for(int i = 0; i<t.length(); i++){
    18             map[t.charAt(i)]--;
    19         }
    20         for(int i = 0; i<256; i++){
    21             if(map[i] != 0){
    22                 return false;
    23             }
    24         }
    25         return true;
    26     }
    27 }

    这道题可以直接sort 两个string 然后比较,相同就返回true.

    不过要注意for Strings, equals() method works as str1.equals(str2). for Arrays, equals() method works as Arrays.equals(arr1, arr2).

    Time Compleixty: O(nlogn). 有sort在内.

    Space: O(n), string换成了char array.

    Method 2:

     1 public class Solution {
     2     public boolean isAnagram(String s, String t) {
     3          //Method 2
     4         char[] temp1 = s.toCharArray();
     5         char[] temp2 = t.toCharArray();
     6         Arrays.sort(temp1);
     7         Arrays.sort(temp2);
     8         
     9         return Arrays.equals(temp1,temp2);
    10     }
    11 }

    跟上Find All Anagrams in a StringGroup Anagrams.

  • 相关阅读:
    centos 关于防火墙的命令
    jsp 时间格式
    @OneToMany
    CentOS7 关闭防火墙
    Centos系统中彻底删除Mysql数据库
    电脑装windows与Centos双系统时引导问题
    如何用C#代码查找某个路径下是否包含某个文件
    计算机中的正斜杠(/)与反斜杠()的区别
    MVC小例子
    vs怎么创建MVC及理解其含义
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4825056.html
Copyright © 2011-2022 走看看