java 最长字串_查找最长子串的长度(不重复字符)

给定"abcabcbb"的答案是"abc",长度是3。

给定"bbbbb"的答案是"b",长度为1。

给定"pwwkew"的答案是"wke",长度为3.请注意,答案必须是子字符串,"pwke"是子序列,而不是子字符串。

我的方法:(时间复杂度较大)

public static int lengthOfLongestSubstring(String s) {

int start, end;

String count = "";

String str = "";

for(start=0; start

for(end=start+1; end<=s.length(); end++){

str = s.substring(start, end);

if(end == s.length()){

if(count.length() < str.length()){//对比长度

count = str;

}

break;

}else{

if(str.contains(s.substring(end, end+1))){//当有重复时候,处理,跳出循环让start++

if(count.length() < str.length()){//对比长度

count = str;

}

break;

}

}

}

}

return count.length();

}

LeetCode给出的方法:

1、假设有一个函数allUnique(),能检测某字符串的子串中的所有字符都是唯一的(无重复字符),那么就可以实现题意描述:

public class Solution {

public int lengthOfLongestSubstring(String s) {

int n = s.length();

int ans = 0;

for (int i = 0; i < n; i++)

for (int j = i + 1; j <= n; j++)

if (allUnique(s, i, j)) ans = Math.max(ans, j - i);

return ans;

}

public boolean allUnique(String s, int start, int end) {

Set set = new HashSet<>();

for (int i = start; i < end; i++) {

Character ch = s.charAt(i);

if (set.contains(ch)) return false;

set.add(ch);

}

return true;

}

}

2、滑动窗口思想:如果确定子串s[i,j](假设表示字符串的第i个字符到第j-1个字符表示的子串),那么只需要比较s[j]是否与子串s[i,j]重复即可

若重复:记录此时滑动窗口大小,并与最大滑动窗口比较,赋值。然后滑动窗口大小重定义为1,头位置不变,并右移一个单位。

若不重复:滑动窗口头不变,结尾+1,整个窗口加大1个单位。继续比较下一个。

public class Solution {

public int lengthOfLongestSubstring(String s) {

int n = s.length();

Set set = new HashSet<>();

int ans = 0, i = 0, j = 0;

while (i < n && j < n) {

// try to extend the range [i, j]

if (!set.contains(s.charAt(j))){

set.add(s.charAt(j++));

ans = Math.max(ans, j - i);

}

else {

set.remove(s.charAt(i++));

}

}

return ans;

}

}

3、使用HashMap

public class Solution {

public int lengthOfLongestSubstring(String s) {

int n = s.length(), ans = 0;

Map map = new HashMap<>(); // current index of character

// try to extend the range [i, j]

for (int j = 0, i = 0; j < n; j++) {

if (map.containsKey(s.charAt(j))) {

i = Math.max(map.get(s.charAt(j)), i);

}

ans = Math.max(ans, j - i + 1);

map.put(s.charAt(j), j + 1);

}

return ans;

}

}

4、

public class Solution {

public int lengthOfLongestSubstring(String s) {

int n = s.length(), ans = 0;

int[] index = new int[128]; // current index of character

// try to extend the range [i, j]

for (int j = 0, i = 0; j < n; j++) {

i = Math.max(index[s.charAt(j)], i);

ans = Math.max(ans, j - i + 1);

index[s.charAt(j)] = j + 1;

}

return ans;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值