leetcode算法题(一)

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;
		}
	}
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值