实施一个efficent算法找到两个字符串的交点 [英] Implementing an efficent algorithm to find the intersection of two strings
本文介绍了实施一个efficent算法找到两个字符串的交点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
实现一个算法,需要两个字符串作为输入,并返回两个的交点,与每个字母重新presented至多一次。
算法中:(使用将是C#语言的考虑)
- 在转换两个字符串转换成char数组
- 乘坐小数组并生成一个哈希表,它与主要的特征和值0
- 现在,遍历其它阵列,并增加在哈希表计数如果char是present在里面。
- 现在,采取了所有字符的哈希表的值> 0
- 在这些交叉点的值。
这是一个O(n)的解决方案,而是使用了额外的空间,2字符数组和一个哈希表
你们可以想到比这更好的解决办法吗?
解决方案
这个怎么样?
VAR S1 =aabbccccddd;
VAR S2 =AABC;
变种ANS = s1.Intersect(S2);
Implement an algorithm that takes two strings as input, and returns the intersection of the two, with each letter represented at most once.
Algo: (considering language used will be c#)
- Convert both strings into char array
- take the smaller array and generate a hash table for it with key as the character and value 0
- Now Loop through the other array and increment the count in hash table if that char is present in it.
- Now take out all char for hash table whose value is > 0.
- These are intersection values.
This is an O(n), solution but is uses extra space, 2 char arrays and a hash table
Can you guys think of better solution than this?
解决方案
How about this ...
var s1 = "aabbccccddd";
var s2 = "aabc";
var ans = s1.Intersect(s2);
这篇关于实施一个efficent算法找到两个字符串的交点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文