1、判断是否是颠倒字母顺序构成的字
class Anagram {
public:
vector<string> anagrams(vector<string> &strs)
{
map<string, vector<string> > group;
for (const auto &s : strs) {
string key = s;
sort(key.begin(), key.end());
group[key].push_back(s);
}
vector<string> result;
for (auto it = group.cbegin(); it != group.cend(); it++) {
if (it->second.size() > 1)
result.insert(result.end(), it->second.begin(), it->second.end());
}
return result;
}
};
2、判断简单路径
class Path
{
public:
void start()
{
string path;
while(getline(cin,path))
{
get_path(path);
}
}
private:
void get_path(string &path)
{
vector<string> result;
for(auto i=path.begin();i<path.end();i++)
{
auto tem=find(i,path.end(),'/'); //找到第一个斜杠
string str=string(i,tem);
if(!str.empty()&&str!=".")
{
if(str=="..")
{
if(!result.empty())
result.pop_back();
}
else
{
result.push_back(str);
}
}
i=tem;
}
if(result.empty())
cout<<"/"<<endl;
else
{
for(auto i=result.begin();i<result.end();i++)
{
cout<<"/"<<*i;
}
cout<<endl;
}
}
};
3、括号匹配
class ValidParentheses {
public:
bool isValid (string const& s) {
string left = "([{";
string right = ")]}";
stack<char> stk;
for (auto c : s) {
if (left.find(c) != string::npos) {
stk.push (c);
} else {
if (stk.empty () || stk.top () != left[right.find (c)])
return false;
else
stk.pop ();
}
}
return stk.empty();
}
};
4、最长括号匹配
class LongestValidParentheses
{
public:
void start() //时间复杂度为o(n),空间复杂度为o(1)
{
string input;
while(getline(cin,input))
{
vector<char> result;
int sum=0;
for(auto i:input)
{
if(i=='(')
result.push_back(i);
if(i==')')
{
if(result.empty()||result.back()!='(')
continue;
if(result.back()=='(')
{
result.pop_back();
sum+=2;
}
}
}
cout<<sum<<endl;
}
}
void start2() //时间复杂度为o(n),空间复杂度为o(1)
{
string input;
while(getline(cin,input))
{
int start=-1,sum=0;
int depth=0;
for(size_t i=0;i<input.size();i++)
{
if(input[i]=='(')
depth++;
else
{
depth--;
if(depth<0)
{
start=i;
depth=0;
}
else if(depth==0)
sum=sum>(i-start)?sum:(i-start);
}
}
depth=0;
start=input.size();
for(int i=start-1;i>=0;--i)
{
if(input[i]==')')
depth++;
else
{
depth--;
if(depth<0)
{
start=i;
depth=0;
}
else if(depth==0)
{
sum=sum>(start-i)?sum:(start-i);
}
}
}
cout<<sum<<endl;
}
}
};