算法初体验-3

早想做一下字符串的题,这个字符串题,自己感觉很经典,同样也是用了哈希表,把通常的O(n2),O(n3)变成了O(n)

Longest Substring Without Repeating Characters

  Total Accepted: 52607  Total Submissions: 245781 My Submissions

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

Show Tags
Have you met this question in a real interview? 
Yes
 
No

Discuss

java 代码实现


public class Longest_Substring_Without_Repeating_Characters {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
	int a	=lengthOfLongestSubstring("adbcded");
	System.out.println(a);
	}
	 public static int lengthOfLongestSubstring(String s) 
	 { char[] arr = s.toCharArray();
	 int max=0;
		int begin=0;
		int end=0;
		HashSet<Character> characters=new HashSet<Character>();
		while(end<arr.length)
		{
			if(characters.contains(arr[end]))
			{
				while(begin<end&&arr[begin]!=arr[end])
				{
					characters.remove(arr[begin]);
					begin++;
				}
				begin++;end++;
			}
			else
			{
				characters.add(arr[end]);
				end++;
			}
			 max = Math.max(max,end-begin);
		}
		return max;
	 }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值