JS to find the most frequently-seen characters in a string

Source: Internet
Author: User

I have seen such a pen question before, and I have worked it out in the traditional way. I have nothing to worry about and think about it. I suddenly got inspiration. The idea is as follows:

1. sort the strings using the sort method of the array so that all the same letters can go together.

2. Use a regular expression to match two adjacent different characters with a comma in the middle

3. Split the strings obtained in step 2 into Arrays Using commas as the bounds.

4. Sort the array by string length. The first element obtained is the answer.

The Code is as follows (Thank you very much for reminding me that the regular expression has been corrected)

String. count = function (str) {var ret = str. split (""). sort (). join (""). replace (/((.) \ 2 *)/g, "$1 ,"). split (","). sort (function (a, B) {return B. length-a.length}); return [ret [0] [0], ret [0]. length];} var s = "& (& $ # (jflsdjfoiwefdjsklfewosd2316907345asdsdwsdqs"; alert (String. count (s ));

The returned value is ['s', 6].

The problem is that the regular expression is not well written, and a comma is added at the end of the string. Then, the last element of the ret array is a null string. if you have any good solutions, please contact us.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.