3. Longest Substring Without Repeating Characters

来源:互联网 发布:支付宝java服务端demo 编辑:程序博客网 时间:2024/05/21 16:58

3. Longest Substring Without Repeating Characters
 *   QuestionEditorial Solution  My Submissions

Difficulty: Medium
Contributors: Admin
Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems

 

一开始写的代码,仿佛是太年轻了,问题没有考虑全面

public static void main(String[] args) {String str="pwwkew";LongestSubstring lon=new LongestSubstring();int i=lon.lengthOfLongestSubstring(str);System.out.println(i);}  public int lengthOfLongestSubstring(String s) {  String substring=null;  int m = 0,max=0;  int i,j = 0;  if(s.length()==1)return 1;  for( i=0;i<s.length();i++){  for(j=i+1;j<s.length();j++){  if(s.charAt(i)==s.charAt(j)){  substring=s.substring(i, j);  //System.out.println(substring);   m=substring.length();   if(max<m){   max=m;   } break;   }   }   }         return max;  }

网上看了别人的代码,并做了注释和测试:

public class LongestSubstring {public static void main(String[] args) {LongestSubstring lx=new LongestSubstring();System.out.println(lx.lengthOfLongestSubstring("pwwkew"));}public int lengthOfLongestSubstring(String s) {   if(s==null || s.length()==0)        return 0;     Set<Character> set = new HashSet<Character>();     int max=0;     int i=0;    int start=0;    while(i<s.length()){    //Returns the char value at the specified index.        char c = s.charAt(i);        //set.contains(c) Returns true if this set contains the specified element.       // System.out.println(set.contains(c));        if(!set.contains(c)){            set.add(c);        }else{        //max(int a, int b)         //Returns the greater of two int values.        //pwwkew            max = Math.max(max, set.size());             while(start<i&&s.charAt(start)!=c){                set.remove(s.charAt(start));                start++;            }            start++;        }         i++;    }     max = Math.max(max, set.size());     return max;}}



 

0 0
原创粉丝点击