题目来源:1763. 最长的美好子字符串
2022.02.01每日一题
法一:暴力解法
暴力求解每一种可能的字符串,从其中选中最优的结果
具体代码已经注释如下
class Solution {
public:
string longestNiceSubstring(string s) {
string res = "";
for (int i = 0; i < s.size(); i++) {
for (int j = i + 1; j < s.size(); j++) {
if (j - i + 1 > res.size() && check(s.substr(i, j - i + 1))) {
res = s.substr(i, j - i + 1);
}
}
}
return res;
}
bool check(string s) {
set<char> Count;
for (char ch: s) {
Count.insert(ch);
}
for (char ch: s) {
char temp1 = tolower(ch), temp2 = toupper(ch);
if (!Count.count(temp1) || !Count.count(temp2)) {
return false;
}
}
return true;
}
};
class Solution {
public String longestNiceSubstring(String s) {
String res = "";
for (int i = 0; i < s.length(); i++) {
for (int j = i + 1; j < s.length(); j++) {
if (j - i + 1 > res.length() && check(s.substring(i, j + 1))) {
res = s.substring(i, j + 1);
}
}
}
return res;
}
public boolean check(String s) {
Set<Character> count = new HashSet<>();
for (char ch : s.toCharArray()) {
count.add(ch);
}
for (char ch : s.toCharArray()) {
char temp1 = Character.toLowerCase(ch), temp2 = Character.toUpperCase(ch);
if (!count.contains(temp1) || !count.contains(temp2)) {
return false;
}
}
return true;
}
}
测试的数据长度最长是 100 ,两次循环时间复杂度是O(n2),空间复杂度O(1)
|