字符串系列编程题

Leetcode 3

求无重复字符的最长子串

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

思路:

判断字符串为空的情况。

把字符串转换为数组。

创建一个大数组用来保存当前所有字母上一次出现的位置,没出现过就填-1。

假设一个子串开始的位置start。

遍历字符串数组,查找到当前遍历的字母上一次出现的位置:

如果上一次出现的位置在start之后,迭代当前最长子串长度为:max((当前遍历索引-上一次位置),之前最长的子串长度),并且需要更新start到上一次出现位置的后一位。

如果上一次出现的位置在start之前,迭代当前最长子串长度为:max((当前遍历索引-start+1),之前最长的子串长度)

在每次遍历完成前还需要将当前遍历到的字母的位置写入记录上一次出现位置的数组中。

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int length = s.length();
        if(s==null || length==0) return 0;
        char [] chars = s.toCharArray();
        int [] lastIndex = new int[128];//存放所有字母上一次出现的位置
        Arrays.fill(lastIndex,-1);//初始化默认均为-1,表示没出现过该字符

        int start = 0, count = 0;
        for(int i=0; i<length; i++){
            int last = lastIndex[chars[i]];//取出当前字符上一次出现的位置
            if(last<start){
                count = Math.max(count,i-start+1);
            }else{
                count = Math.max(count,i-last);
                start = last+1;//更新字符串开始位置
            }
            lastIndex[chars[i]]=i;//更新当前字符上一次出现的位置
        }
        return count;
    }
}

 

牛客NC103

反转字符串

将字符串转化为数组,双指针不断交换首末元素。最后用StringBuffer存放后再转化为字符串返回。

import java.util.*;
public class Solution {
    public String solve (String str) {
        int l = 0, h = str.length()-1;
        char [] chars = str.toCharArray();
        while(l<h){
            char tmp = chars[l];
            chars[l] = chars[h];
            chars[h] = tmp;
            l++;
            h--;            
        }
        StringBuffer sb = new StringBuffer();
        for(char c:chars){
            sb.append(c);
        }
        return sb.toString();        
    }
}

 

posted @ 2020-09-13 16:52  菅兮徽音  阅读(566)  评论(0)    收藏  举报