首页 >  资讯 >  详情

LeetCode 1763. Longest Nice Substring 世界观点

2023-04-09 10:04:34来源:哔哩哔哩

A string sis nice if, for every letter of the alphabet that scontains, 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 sthat is nice. If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string.


(资料图)

Example 1:

Input: s = "YazaAay"

Output: "aAa"

Explanation: "aAa" is a nice string because 'A/a' is the only letter of the alphabet in s, and both 'A' and 'a' appear."aAa" is the longest nice substring.

Example 2:

Input: s = "Bb"

Output: "Bb"

Explanation: "Bb" is a nice string because both 'B' and 'b' appear. The whole string is a substring.

Example 3:

Input: s = "c"

Output: ""

Explanation: There are no nice substrings.

Constraints:

1 <= s.length <= 100

sconsists of uppercase and lowercase English letters.‘

题目不难,就是写的code长了一点,先是要判断是否是nice string,用数组最快了,

然后遍历整个字符串,条件是当j-i+1没在hashmap中,因为如果在了,说明前面已经有这么长的字符串满足要求了,所以就不需要判断的,如果是nice string,就把长度跟左右端的index放到map中,然后遍历map,找到最长的,返回即可(如果map.size>1的情况下),map如果是空的就返回空字符串即可。

Runtime: 13 ms, faster than 30.49% of Java online submissions for Longest Nice Substring.

Memory Usage: 42.6 MB, less than 30.32% of Java online submissions for Longest Nice Substring.

关键词:

[ 相关文章 ]