البرمجة

كيفية العثور على الأناقرامات في مصفوفة السلاسل النصية

To check if two strings are anagrams, you can create a hash function that maps each string to a unique value based on its characters. One common approach is to sum the ASCII values of all characters in the string. However, this approach may not be sufficient to uniquely identify anagrams, as different strings can have the same sum of ASCII values.

A better approach is to use a hash function that calculates a unique value for each string based on the frequency of each character. One way to do this is to create a frequency map for each string, where the key is the character and the value is the frequency of that character in the string. You can then use this map to calculate a unique hash value for each string.

Here’s an example of how you could implement such a hash function and use it to find groups of anagrams in an array of strings:

java
public class Solution { private String getHash(String s) { int[] freq = new int[26]; // Assuming only lowercase letters for (char c : s.toCharArray()) { freq[c - 'a']++; } StringBuilder hash = new StringBuilder(); for (int f : freq) { hash.append(f); } return hash.toString(); } public ArrayList> anagrams(final List a) { HashMap> map = new HashMap<>(); for (int i = 0; i < a.size(); i++) { String hash = getHash(a.get(i)); if (!map.containsKey(hash)) { map.put(hash, new ArrayList()); } map.get(hash).add(i + 1); } ArrayList> result = new ArrayList<>(); for (ArrayList indices : map.values()) { if (indices.size() > 1) { result.add(indices); } } return result; } }

In this implementation, the getHash method calculates a unique hash for each string based on the frequency of characters. The anagrams method then uses this hash function to group strings that have the same hash value, indicating that they are anagrams of each other.

المزيد من المعلومات

بالتأكيد، إليك المزيد من المعلومات:

  1. يقوم الكود بتحويل كل سلسلة نصية إلى قيمة هاش من خلال حساب تردد كل حرف في السلسلة وتخزينها في مصفوفة الترددات. ثم يتم بناء سلسلة نصية تحتوي على تردد كل حرف معًا لتكون قيمة الهاش النهائية.
  2. تستخدم الدالة anagrams هاشات السلاسل النصية لتجميع السلاسل النصية التي تشير إلى نفس الهاش، مما يعني أنها تحتوي على نفس الأحرف بترتيب مختلف، وتضيف مؤشراتها إلى قائمة تخزينها.
  3. يتم تجميع كل هذه القوائم في قائمة نهائية تحتوي على مؤشرات السلاسل النصية التي تشكل مجموعة واحدة من الأناقرامات.

هذا النهج يضمن فصل السلاسل النصية إلى مجموعات من الأناقرامات بفعالية وسرعة بفضل استخدام الهاشات لتمثيل السلاسل وتجميعها.

مقالات ذات صلة

زر الذهاب إلى الأعلى
إغلاق

أنت تستخدم إضافة Adblock

يرجى تعطيل مانع الإعلانات حيث أن موقعنا غير مزعج ولا بأس من عرض الأعلانات لك فهي تعتبر كمصدر دخل لنا و دعم مقدم منك لنا لنستمر في تقديم المحتوى المناسب و المفيد لك فلا تبخل بدعمنا عزيزي الزائر