Implementing an efficent algorithm to find the intersection of two strings

前端 未结 5 1924
挽巷
挽巷 2020-12-18 13:29

Implement an algorithm that takes two strings as input, and returns the intersection of the two, with each letter represented at most once.

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-18 13:44

    You don't need to 2 char arrays. The System.String data type has a built-in indexer by position that returns the char from that position, so you could just loop through from 0 to (String.Length - 1). If you're more interested in speed than optimizing storage space, then you could make a HashSet for the one of the strings, then make a second HashSet which will contain your final result. Then you iterate through the second string, testing each char against the first HashSet, and if it exists then add it the second HashSet. By the end, you already have a single HashSet with all the intersections, and save yourself the pass of running through the Hashtable looking for ones with a non-zero value.

    EDIT: I entered this before all the comments on the question about not wanting to use any built-in containers at all

提交回复
热议问题