Skip to content
This repository has been archived by the owner on Oct 17, 2023. It is now read-only.

Added valid_anagram.java #542

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions JAVA/valid_anagram.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// https://leetcode.com/problems/valid-anagram/
/* Given two strings s and t, return true if t is an anagram of s, and false otherwise.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.



Example 1:

Input: s = "anagram", t = "nagaram"
Output: true
Example 2:

Input: s = "rat", t = "car"
Output: false


Constraints:

1 <= s.length, t.length <= 5 * 104
s and t consist of lowercase English letters. */

class valid_anagram {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
int characters[] = new int[26];
for (int i = 0; i < s.length(); i++) {
characters[s.charAt(i) - 'a']++;
characters[t.charAt(i) - 'a']--;
}
for (int alphabet : characters) {
if (alphabet != 0) {
return false;
}
}
return true;
}

public static void main(String args[]) {
String s = "anagram";
String t = "nagaram";
valid_anagram va = new valid_anagram();
System.out.println(va.isAnagram(s, t));
}
}