【每日一题-7】min栈实现与第一次只出现两次的字符
2017-07-21 18:39
204 查看
实现一个栈Stack,要求实现Push(出栈)、Pop(入栈)、Min(返回最小值的操作)的时间复杂度为O(1)
#include<iostream>
#include<stack>
using namespace std;
template<class T>
class Stack
{
public:
void Push(const T data)
{
s1.push(data);
int top = s1.top();
if (s2.empty())
s2.push(top);
else
{
if (!s1.empty() && s1.top() < s2.top())
{
s2.push(s1.top());
}
s1.pop();
}
}
void Pop()
{
if (!s1.empty())
{
s1.pop();
}
}
int Min()
{
return s2.top();
}
protected:
stack<int> s1;
stack<int> s2;
};
查找一个字符串中第一个只出现两次的字符。比如:“abcdefabcdefabc”中第一个只出现两次为‘d’,要求时间复杂度为O(N),空间复杂度为O(1)
#include<assert.h>
char FindFirstCh(char* str, size_t n)
{
assert(str&& n);
char arr[256] = { 0 }; //记录字符出现的个数
int count[256] = { 0 }; //记录字符出现的次数
for (size_t i = 0; i < n; i++)
{
arr[str[i]]++;
count[str[i]] = i;
}
for (size_t i = 0; i < n; i++)
{
if (count[i] && arr[i] == 2) //如果该字符出现两次,且是第一次出现的
return arr[i];
}
return NULL; //没有出现两个字符的情况
}
#include<iostream>
#include<stack>
using namespace std;
template<class T>
class Stack
{
public:
void Push(const T data)
{
s1.push(data);
int top = s1.top();
if (s2.empty())
s2.push(top);
else
{
if (!s1.empty() && s1.top() < s2.top())
{
s2.push(s1.top());
}
s1.pop();
}
}
void Pop()
{
if (!s1.empty())
{
s1.pop();
}
}
int Min()
{
return s2.top();
}
protected:
stack<int> s1;
stack<int> s2;
};
查找一个字符串中第一个只出现两次的字符。比如:“abcdefabcdefabc”中第一个只出现两次为‘d’,要求时间复杂度为O(N),空间复杂度为O(1)
#include<assert.h>
char FindFirstCh(char* str, size_t n)
{
assert(str&& n);
char arr[256] = { 0 }; //记录字符出现的个数
int count[256] = { 0 }; //记录字符出现的次数
for (size_t i = 0; i < n; i++)
{
arr[str[i]]++;
count[str[i]] = i;
}
for (size_t i = 0; i < n; i++)
{
if (count[i] && arr[i] == 2) //如果该字符出现两次,且是第一次出现的
return arr[i];
}
return NULL; //没有出现两个字符的情况
}
相关文章推荐
- 给定一字符串,求字符串中第一次出现的非重复的字符,例如abaaedgff,输出b.(Java 实现)
- 【每日一题】查找一个字符串中第一个只出现两次的字符。要求时间复杂度为O(N),空间复杂度为O(1)
- 【每日一题】查找一个字符串中第一个只出现两次的字符
- 【C语言】模拟实现strchr函数.即在一个字符串中查找一个字符第一次出现的位置并返回
- 【c语言】模拟实现strchr函数,功能:在一个字符串中查找一个字符第一次出现的位置,如果没有出现返回NULL
- 实现一个栈Stack,要求实现Push(出栈)、Pop(入栈)、Min(返回最小值的操作)的时间复杂度为O(1) /查找一个字符串中第一个只出现两次的字符
- 实现删除字符串中出现次数最少的字符,若多个字符出现次数一样,则都删除。
- 在一个字符串中找出第一次重复出现的字符
- loadrunner通过C语言实现自定义字符出现次数截取对应字符串
- 请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字
- 每日微软面试题——day 7(找数组中唯一出现两次的数)
- SQL获取第一次出现指定字符前的内容
- 【字符串】查找一个字符串中第一个只出现两次的字符。比如:“abcdefabcdefabc”中第一个只出现两次为‘d’,要求时间复杂度为O(N),空间复杂度为O(1)
- 【算法】每日微软面试题——day 7(找数组中唯一出现两次的数)
- 冒泡算法、二叉搜索树转双向链表、字符串第一个只出现一次字符C#实现
- 查找一个字符串中第一个只出现两次的字符。比如:“abcdefabcdefabc”中第一个只出现两次为‘d’,要求时间复杂度为O(N),空间复杂度为O(1)
- 华为机试:将字符串里第一次出现的字符输出,重复出现的不显示
- 第一次只出现一次的字符
- 递归实现一个去除字符串中“重复出现的字符”
- 查找一个字符串中第一个只出现两次的字符。比如:“abcdefabcdefabc”中第一个只出现两次为‘d’,要求时间复杂度为O(N),空间复杂度为O(1)