0
点赞
收藏
分享

微信扫一扫

【LeeCode】无重复字符的最长子序列(自测)

【题目描述】

给定一个字符串 ​s​ ,请你找出其中不含有重复字符的 最长子序列

【示例】

输入: s = "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3

示例: 注意 pwke是子序列 非子串

输入: s = "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。


【代码】

package com.company;

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class longest_str_without_repeating_characters {
public static void main(String[] args) {
String str = "pwwkew";
get_longest_str_without_repeating_characters(str);
}

/**
* 1. 传入的字符串一定要判空
* 2. sb添加str.charAt(0) 所以 max的起始值是 1
*/
private static int get_longest_str_without_repeating_characters(String str) {
int len = str.length();
// 处理str为空的情况
if(len == 0 || str.equals(""))
return 0;
List<String> list = new ArrayList<>();
StringBuffer sb = new StringBuffer();
sb.append(str.charAt(0));
int max = 1;
for(int i = 1; i < str.length(); i++){
char ch = str.charAt(i);
if(sb.toString().indexOf(ch) < 0){
// 不存在这个字符
sb.append(ch);
if(sb.length() >= max){
max = sb.length();
}else{
sb = new StringBuffer();
sb.append(ch);
}
}
if(sb.length() >= max){
list.add(sb.toString());
}
}
System.out.println(list.toString());
System.out.println(max);
return 0;
}
}


举报

相关推荐

0 条评论