forked from MakeContributions/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
chore(Go): add anagram (MakeContributions#834)
- Loading branch information
1 parent
7db2f01
commit 7f85abf
Showing
2 changed files
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -27,4 +27,5 @@ | |
|
||
## String | ||
- [Palindrome Permutation](strings/palindrome-permutation.go) | ||
- [Anagram](strings/anagram.go) | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
package main | ||
|
||
/** | ||
Problem Statement: Given two strings s and t, find they are anagrams or not | ||
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 | ||
***/ | ||
|
||
/*** | ||
Time complexity: O(n), n=length of string s | ||
Space complexity: O(1) | ||
**/ | ||
|
||
import "fmt" | ||
|
||
func main() { | ||
fmt.Println("Enter first string") | ||
var first string | ||
fmt.Scanln(&first) | ||
fmt.Println("Enter second string") | ||
var second string | ||
fmt.Scanln(&second) | ||
ans := isAnagram(first, second) | ||
if ans == true { | ||
fmt.Println("They are anagrams") | ||
} else { | ||
fmt.Println("They are not anagrams") | ||
} | ||
} | ||
func isAnagram(s string, t string) bool { | ||
var count [256]int | ||
//var i int | ||
for i := 0; i < len(s); i++ { | ||
count[s[i]]++ | ||
} | ||
for i := 0; i < len(t); i++ { | ||
count[t[i]]-- | ||
} | ||
for i := 0; i < len(count); i++ { | ||
if count[i] != 0 { | ||
return false | ||
} | ||
} | ||
return true | ||
} |