【备战字节面试】算法特训-字符串

296 阅读1分钟

简单粗暴,记录备战过程,持续更新

字符串

字符串大家太熟了,不过算法题可不简单。解题思路一样,但是每个语言的实现可打不同,熟悉默写jdk函数。

适用场景

实战

实战1,leetcode 5. 最长回文子串

1, 可以暴力解法, 2,动态规划

  • 状态
  • 转移方程
  • 边界条件
class Solution {
    public String longestPalindrome(String s) {
        int len = s.length();
        if(len < 2){
            return s;
        }
        boolean[][] dp = new boolean[len][len];
        for(int i = 0 ; i < len ; i++){
            dp[i][i] = true;
        }
        int begin = 0;
        int maxLen = 0;
        char[] arr = s.toCharArray();
        for(int j = 1 ; j < len ; j++){
            for(int i = 0 ; i < len - 1  ; i++){
                // (j - 1) - (i + 1) + 1 < 2 
                if(j - i < 3 ){
                    dp[i][j] = true;
                }
                if(arr[i] != arr[j]){
                    dp[i][j] = false;
                }else{
                    dp[i][j] = dp[i+1][j-1];
                    if(j - i + 1 > maxLen){
                        begin = i;
                        maxLen = j - i + 1;
                    }
                }
            }
        }
        return s.substring(begin,maxLen);
    }
}

实战2,leetcode 14. 最长公共前缀

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs.length == 1){
            return strs[0];
        }
        int ret = commonPre(0,strs);
        return strs[0].substring(0,ret);
    }

    private static int commonPre(int index, String[] strs) {
        if (strs[0].length() <= index) {
            return index;
        }
        char tmp = strs[0].charAt(index);
        int count = 1;
        for (int i = 1; i < strs.length; i++) {
            if (strs[i].length() <= index) {
                break;
            }
            if (strs[i].charAt(index) == tmp) {
                count++;
            }
        }
        if (count == strs.length) {
            return commonPre(index + 1, strs);
        }
        return index ;
    }
}

实战3 leetcode 3. 无重复字符的最长子串

import java.util.*;

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int len = s.length();
        if(s == null ||  len == 0){
            return 0;
        }
        int maxLen = 0;
        // 是否重复集合
        Set<Character> set = new HashSet<>();
        // 快慢指针
        int slow = -1;
        int fast = 0;
        while(fast < len){
            // 当前
            char tmp = s.charAt(fast);
            // 不包含,添加
            if(!set.contains(tmp)){
                set.add(tmp);
                int tmpLen = fast - slow;
                maxLen = Math.max(tmpLen,maxLen);
                fast++;
            }
            // 包含
            else{
                slow++;
                set.remove(s.charAt(slow));
            }
        }
        return maxLen;
    }
}

实战4 leetcode 76. 最小覆盖子串