Main Menu

Valid Anagram

Started by kevin, May 31, 2024, 10:58:47 AM

Previous topic - Next topic

kevin

Valid Anagrams

How do you detect if two strings are anagrams or not in PlayBASIC ?    This is one of those coding questions that popped up in my socials recently.  On the surface all we need do is check if the two strings contain the same letters, if they do, they're anagrams.

Assuming the strings only contain alphabetically characters in lower case (a,b,c etc etc x,y,z) , we can use an array to count the number of times each character occurs.  So we could do this two both strings and them compared the counts, if no differences are found the two strings are indeed anagrams.    But that requires two tables

However you can just use one integer array and simply add and subtract one for each occurrence of each character within the array.  Which is how the following solution works. 




242. 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.




PlayBASIC Code: [Select]
    print IsAnagram("anagram"    , "nagaram")
print IsAnagram("rat" , "car")

sync
waitkey



function IsAnagram(A$, B$)
// dumpg to debug
#print "IsAnagram("+A$+","+B$+")"

// Are these even the same size ?? , if not exit
local A_size =len(A$)
local B_size =len(B$)
if A_Size<>B_Size then exitfunction false

Dim CharacterMAP(asc("z"))
for lp =1 to A_Size
CharacterMAP(mid(a$,lp)-asc("a"))++
CharacterMAP(mid(b$,lp)-asc("a"))--
next

for lp =0 to asc("z")- asc("a")
if CharacterMap(lp)<>0
exitfunction false
endif
next

endfunction true