码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 3:LongestSubString

时间:2015-06-06 10:25:13      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

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.

System.out.println(str1.indexOf("c")) ; // 查到返回位置,基值为0
System.out.println(str1.indexOf("c",3)) ; // 查到返回位置,从第4个位置开始查找
System.out.println(str1.indexOf("x")) ; // 没有查到返回-1

System.out.println(str1.substring(6)) ; // 从第7个位置开始截取
System.out.println(str1.substring(0,5)) ; // 截取0~5个位置的内容

System.out.println(str1.charAt(3)) ; // 取出字符串中第四个字符

技术分享
 1 public class Solution {
 2     public int lengthOfLongestSubstring(String s) {
 3         int l=s.length();
 4         if(l==0){
 5             return l;
 6         }
 7         int i=0;
 8         int j=0;
 9         String ans=new String();
10         String sub=new String();
11         while(i<l){
12             if(!sub.contains(String.valueOf(s.charAt(i)))){
13                 sub+=s.charAt(i);
14             }else{
15                 ans=ans.length()>sub.length()?ans:sub;
16                 
17                 //j=i-(sub.length()-sub.indexOf(s.charAt(i)));
18                 j=sub.indexOf(s.charAt(i));
19                 //if(j<sub.length()){
20                     sub=sub.substring(j+1);
21                 sub+=s.charAt(i);
22                 //}else if(j==sub.length()){
23                   //  sub=String.valueOf(s.charAt(i));
24                   
25                //}
26                 
27             }
28             i++;
29             
30         }
31         ans=ans.length()>sub.length()?ans:sub;
32         return ans.length();
33     }
34 }
View Code

 

LeetCode 3:LongestSubString

标签:

原文地址:http://www.cnblogs.com/gonewithgt/p/4556122.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!