leetcode-242.Valid Anagram

题目

Given two strings s and t , write a function to determine if t is an anagram of s.

Example 1:

Input: s = “anagram”, t = “nagaram”
Output: true

Example 2:

Input: s = “rat”, t = “car”
Output: 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?

思路1:排序

将两个字符串分别转换为字符数组并调用Arrays.sort()方法对字符数组进行排序,并判断排序后的数组是否相同
时间复杂度:涉及到排序,为O(nlgn)

代码

class Solution {
	public boolean isAnagram(String s, String t) {
	    if (s.length() != t.length()) {
	        return false;
	    }
	    char[] str1 = s.toCharArray();
	    char[] str2 = t.toCharArray();
	    Arrays.sort(str1);
	    Arrays.sort(str2);
	    return Arrays.equals(str1, str2);
	}
}

Runtime: 5 ms, faster than 56.20% of Java online submissions for Valid Anagram.
Memory Usage: 36.5 MB, less than 78.36% of Java online submissions for Valid Anagram.

思路2:hashtable

用重复检测的方法来考虑:
用一个数组来纪录字符串中各个字母出现的次数,并且为了节省空间可以只用一个数组完成,遍历一趟,s中的某字母出现一次就让对应位置计数+1,反之,t中字母出现时使计数-1。若t是s的"anagram",那么最后这个counter数组中的所有元素都应该是0。
unicode的情况把数组换成hashtable。

时间复杂度O(n)

代码

class Solution {
	public boolean isAnagram(String s, String t) {
	    if (s.length() != t.length()) {
	        return false;
	    }
	    int[] counter = new int[26];//因为题目规定字符都是小写的,所以用26就能搞定
	    for(int i = 0; i < s.length(); i ++){
	    	counter[s.charAt(i) - 'a']++; // - 'a' 用来找到相对a的偏移值,也就是找到对应计数的位置
	    	counter[t.charAt(i) - 'a']--;

	    }
	    for(int count : counter ){
	    	if(count != 0){
	    		return false;
	    	}

	    }
	    return true;
	}
}

Runtime: 3 ms, faster than 89.10% of Java online submissions for Valid Anagram.
Memory Usage: 34.3 MB, less than 100.00% of Java online submissions for Valid Anagram.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值