今天刷题时猛然发现,c/c++的指针是->写法,忘了都。
leetcode原题:
给你一个字符串 s
和一个整数 repeatLimit
,用 s
中的字符构造一个新字符串 repeatLimitedString
,使任何字母 连续 出现的次数都不超过 repeatLimit
次。你不必使用 s
中的全部字符。
返回 字典序最大的 repeatLimitedString
。
如果在字符串 a
和 b
不同的第一个位置,字符串 a
中的字母在字母表中出现时间比字符串 b
对应的字母晚,则认为字符串 a
比字符串 b
字典序更大 。如果字符串中前 min(a.length,b.length)
个字符都相同,那么较长的字符串字典序更大。
我没想到怎么做,我想到的也是用map来存储两个的出现的次数,然后后面再比较,但是答案我还是没看懂,下面附上代码:
class Solution {
public:
string repeatLimitedString(string s, int repeatLimit) {
string result; //把结果字符添加到result,返回result
map<char,int> freq;
for(char c:s){
freq[c]++;
}
while (!freq.empty()) {
auto it = --freq.end(); // 从 map 末尾(字典序最大字符)开始
char currentChar = it->first;
int count = it->second;
// 如果上一个添加的字符是相同的且已经达到 repeatLimit 次数,则需要插入下一个较小的字符
if (!result.empty() && result.back() == currentChar) {
if (freq.size() == 1) break; // 只有一个字符,无法再插入其他字符
// 寻找下一个较小的字符
auto smallerIt = prev(it);
result += smallerIt->first;
if (--smallerIt->second == 0) {
freq.erase(smallerIt);
}
} else {
// 插入字符,最多插入 repeatLimit 次
int timesToAdd = min(count, repeatLimit);
result.append(timesToAdd, currentChar);
// 更新字符频次
if ((freq[currentChar] -= timesToAdd) == 0) {
freq.erase(currentChar);
}
}
}
return result;
}
};
最老的斐波那契数列题,按理说应该是手到擒来,写出来之后发现自己的运行时间居然是最长的!!!!!
这是我写的:
class Solution {
public:
int fib(int n) {
if(n == 0){
return 0;
}else if(n == 1){
return 1;
}else{
return fib(n-1)+fib(n-2);
}
}
};
时间是13ms,大佬的算法时间用了0ms,my god!!!!
他是创建了一个一维的vector数组,在里面依次去添加斐波那契数:
class Solution {
public:
int fib(int n) {
vector<int> dp;
dp.push_back(0);
dp.push_back(1);
for(int i = 2; i<=n; ++i){
dp.push_back(dp[i-1] + dp[i-2]);
}
return dp[n];
}
};