算法连载4

Problem Statement

 You just bought a very delicious chocolate bar from a local store. This chocolate bar consists of N squares, numbered 0 through N-1. All the squares are arranged in a single row. There is a letter carved on each square. You are given a string letters. The i-th character of letters denotes the letter carved on the i-th square (both indices are 0-based).

You want to share this delicious chocolate bar with your best friend. At first, you want to give him the whole bar, but then you remembered that your friend only likes a chocolate bar without repeated letters. Therefore, you want to remove zero or more squares from the beginning of the bar, and then zero or more squares from the end of the bar, in such way that the remaining bar will contain no repeated letters.

Return the maximum possible length of the remaining chocolate bar that contains no repeated letters.

Definition

 
Class:ChocolateBar
Method:maxLength
Parameters:string
Returns:int
Method signature:int maxLength(string letters)
(be sure your method is public)
 
 

Constraints

-letters will contain between 1 and 50 characters, inclusive.
-Each character of letters will be a lowercase letter ('a' - 'z').

Examples

0) 
 
"srm"
Returns: 3
You can give the whole chocolate bar as it contains no repeated letters.
1) 
 
"dengklek"
Returns: 6
Remove two squares from the end of the bar.
2) 
 
"haha"
Returns: 2
There are three possible ways:
  • Remove two squares from the beginning of the bar.
  • Remove two squares from the end of the bar.
  • Remove one square from the beginning of the bar and one square from the end of the bar.
3) 
 
"www"
Returns: 1
4) 
 
"thisisansrmbeforetopcoderopenfinals"
Returns: 9

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2003, TopCoder, Inc. All rights reserved.     


这个题目蛮简单的,就是要我们找有几个不相同字母。所以每个比过去就行了。

别人的代码:

class ChocolateBar
{
public:
	static int madxLength(strinf str){
		int ans =1;
int pos[30]pre[55];
meset(pos,-1,sizeof(pos));
for(int i=0;i<str.length();i++)
{	
	int c=str[i]-'a';
pre[i]=pos[c];
pos[c]=i;
}
	deque<int> qv ;
qv.push_front(0);
for(int i=1;i<str.length();i++){
	while(!qv.empty())
{	int c=qv.back();
if(pre[v]<=pre[i])
qv.pop_back();
else
break;
}
	qv.push_back(i);
ans=max(ans,i-re[qv.front()]);
}

return ans;
}

};这个代码有点乱还有些东西都编译不出来,好像是编译环境的问题。
还是再来个】
 


这个明显多了


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值