GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — leetcode-1/algorithms/cpp/anagrams/ValidAnagram.cpp at master · mtangm/leetcode-1 Expand file tree/ Copy pathValidAnagram.cppMore file actions 60 lines (46 loc) · 1.53 KB / Copy pathValidAnagram.cppFile metadata and controls60 lines (46 loc) · 1.53 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 // Source : https://leetcode.com/problems/valid-anagram/ // Author : Hao Chen // Date : 2015-08-16 /********************************************************************************** * * Given two strings s and t, write a function to determine if t is an anagram of s. * * For example, * s = "anagram", t = "nagaram", return true. * s = "rat", t = "car", return false. * * Note: * You may assume the string contains only lowercase alphabets. * **********************************************************************************/ class Solution { public: //stupid way - but easy to understand - 76ms bool isAnagram01(string s, string t) { sort(s.begin(), s.end()); sort(t.begin(), t.end()); return s == t; } //using a map to count every chars in the string. bool isAnagram02(string s, string t) { int map[26] ={0} ; //only lowercase alphabets //memset(map, 0, sizeof(map)); // count each char for s for (int i=0; i<s.size(); i++) { map[s[i]-'a']++; } // decrease the count for t for (int i=0; i<t.size(); i++) { map[t[i]-'a']--; } //if all alphabets is zero, then they are anagram for (int i=0; i<sizeof(map)/sizeof(map[0]); i++) { if (map[i]!=0) return false; } return true; } bool isAnagram(string s, string t) { return isAnagram02(s,t); //12ms return isAnagram01(s,t); //76ms } }; |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |