We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
思路分析:
使用一个数组记录字符串S出现的次数,若该字母出现了一次,该位置的元素值加一;再遍历另外一个字符串,若出现一次就在数组对应位置的值减一。
因为字母是按顺序的,ASCII码上,每个字母也是相差1,随便取一个字母减去‘a’,就会得到该字母的下标了,然后在对应的record数组上,让该索引下的值+1
时间复杂度:O(n)
空间复杂度:O(1)
class Solution { public boolean isAnagram(String s, String t) { //哈希法 用数组来实现 //定义一个统计字母出现次数的字符串 int[] record = new int[26];//开辟26个空间即可 for (int i = 0; i < s.length(); i++) { record[s.charAt(i) - 'a']++;//因为字母是按顺序的,ASCII码上,每个字母也是相差1,随便取一个字母减去‘a’,就会得到该字母的下标了,然后在对应的record数组上,让该索引下的值+1 } for (int i = 0; i < t.length(); i++) { record[t.charAt(i) - 'a']--; } //只要record数组里面,不是0的,说明该位置的元素在两个字符串中不相等 for (int count: record) { if (count != 0) { return false; } } return true; } }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
哈希法—数组实现
思路分析:
使用一个数组记录字符串S出现的次数,若该字母出现了一次,该位置的元素值加一;再遍历另外一个字符串,若出现一次就在数组对应位置的值减一。
时间复杂度:O(n)
空间复杂度:O(1)
The text was updated successfully, but these errors were encountered: