"Algorithm" finds the length of the oldest string without repetition

Source: Internet
Author: User
Tags repetition

title : input is a string that finds the length of the oldest string without repeating characters

Example :

" ABCABCBB " the eldest string ( ABC ) Length is 3

" bbbbbbb " the eldest string ( b ) Length is 1

"Abdevbac" eldest string (bdev) Length 4

algorithm Idea :

Set two subscript identifiers, initially at the head of the array, and set a hashset. Identify runner to go backward, and put the passed characters into the hashset, when there is duplicate character, stop moving, at this time, the logo walker chasing after, until Walker's character and runner characters are the same so far, At this point the character between Walker and runner is a string with no duplicates, and the length is recorded as Max. The length value of the longest string can be obtained after a traversal.

Complexity of Time :

Two identities need to be traversed once, i.e. 2*n, so the complexity is: O (N)

Code Implementation :

public int lengthoflongestsubstring (String s) {
if (S==null | | s.length () ==0)
return 0;
hashset<character> set = new hashset<character> ();
int max = 0;
int walker = 0;
int runner = 0;
while (Runner<s.length ())
{
if (Set.contains (S.charat (runner)))
{
while (S.charat (Walker)!=s.charat (runner))
{
Set.remove (S.charat (Walker));
walker++;
}
if (Max<runner-walker)
{
max = Runner-walker;
}
walker++;
}
Else
{
Set.add (S.charat (runner));
}
runner++;
}
max = Math.max (Max,runner-walker);
return Max;
}

"Algorithm" finds the length of the oldest string without repetition

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.