GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • LeetCodeJavascript.com
  • Star on GitHub

This view

  • Original page
  • New address

GeezerVison is showing leetcodejavascript.com — #1763 - Longest Nice Substring - LeetCode JavaScript Solutions

Back to all solutions

#1763 - Longest Nice Substring

Easy • View on LeetCode • View on GitHub
String Hash Table Bit Manipulation Sliding Window Divide and Conquer

Problem Description

A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, "abABB" is nice because 'A' and 'a' appear, and 'B' and 'b' appear. However, "abA" is not because 'b' appears, but 'B' does not.

Given a string s, return the longest substring of s that is nice. If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string.

Solution

/**
 * @param {string} s
 * @return {string}
 */
var longestNiceSubstring = function(s) {
  let longest = '';

  for (let i = 0; i < s.length; i++) {
    for (let j = i; j < s.length; j++) {
      const substr = s.slice(i, j + 1);
      if (substr.length <= longest.length) continue;
      const chars = new Set(substr.toLowerCase().split(''));
      let isNice = true;
      for (const char of chars) {
        if (!substr.includes(char.toLowerCase()) || !substr.includes(char.toUpperCase())) {
          isNice = false;
          break;
        }
      }
      if (isNice) longest = substr;
    }
  }

  return longest;
};
You are visitor 01402520 — 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.