ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

leetcode 5. Longest Palindromic Substring/ 1254. Number of Closed Islands/ 45. Jump Game

2021-09-13 21:32:19  阅读:185  来源: 互联网

标签:return Palindromic int 45 len Jump ++ length grid


文章目录

5. Longest Palindromic Substring

Given a string s, return the longest palindromic substring in s.

Example 1:

Input: s = “babad”
Output: “bab”
Note: “aba” is also a valid answer.
Example 2:

Input: s = “cbbd”
Output: “bb”
Example 3:

Input: s = “a”
Output: “a”
Example 4:

Input: s = “ac”
Output: “a”

Constraints:

1 <= s.length <= 1000
s consist of only digits and English letters.

dynamic O(n^2) O(n^2)

class Solution {
    public String longestPalindrome(String s) {
        int beginIndex=0,endIndex=0;
        int n=s.length();
        boolean[][] dp=new boolean[n][n];

        for(int i=0;i<n;i++)dp[i][i]=true;

        for(int l=2;l<=n;l++){
            for(int i=0;i<=n-l;i++){
                int j=i+l-1;
                dp[i][j]=false;
                if(s.charAt(i)==s.charAt(j)){
                    if(l==2)dp[i][j]=true;
                    else dp[i][j]=dp[i+1][j-1];
                }
                if(dp[i][j]){
                    beginIndex=i;
                    endIndex=j;
                }
            }
        }
        return s.substring(beginIndex,endIndex+1);
    }
}

中心扩展 O(n^2) O(1)

class Solution {
    public String longestPalindrome(String s) {
        if (s == null || s.length() < 1) {
            return "";
        }
        int start = 0, end = 0;
        for (int i = 0; i < s.length(); i++) {
            int len1 = expandAroundCenter(s, i, i);
            int len2 = expandAroundCenter(s, i, i + 1);
            int len = Math.max(len1, len2);
            if (len > end - start) {
                start = i - (len - 1) / 2;
                end = i + len / 2;
            }
        }
        return s.substring(start, end + 1);
    }

    public int expandAroundCenter(String s, int left, int right) {
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            --left;
            ++right;
        }
        return right - left - 1;
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/longest-palindromic-substring/solution/zui-chang-hui-wen-zi-chuan-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

manacher O(n) O(n) (too diffcult)

class Solution {
    public String longestPalindrome(String s) {
        int start = 0, end = -1;
        StringBuffer t = new StringBuffer("#");
        for (int i = 0; i < s.length(); ++i) {
            t.append(s.charAt(i));
            t.append('#');
        }
        t.append('#');
        s = t.toString();

        List<Integer> arm_len = new ArrayList<Integer>();
        int right = -1, j = -1;
        for (int i = 0; i < s.length(); ++i) {
            int cur_arm_len;
            if (right >= i) {
                int i_sym = j * 2 - i;
                int min_arm_len = Math.min(arm_len.get(i_sym), right - i);
                cur_arm_len = expand(s, i - min_arm_len, i + min_arm_len);
            } else {
                cur_arm_len = expand(s, i, i);
            }
            arm_len.add(cur_arm_len);
            if (i + cur_arm_len > right) {
                j = i;
                right = i + cur_arm_len;
            }
            if (cur_arm_len * 2 + 1 > end - start) {
                start = i - cur_arm_len;
                end = i + cur_arm_len;
            }
        }

        StringBuffer ans = new StringBuffer();
        for (int i = start; i <= end; ++i) {
            if (s.charAt(i) != '#') {
                ans.append(s.charAt(i));
            }
        }
        return ans.toString();
    }

    public int expand(String s, int left, int right) {
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            --left;
            ++right;
        }
        return (right - left - 2) / 2;
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/longest-palindromic-substring/solution/zui-chang-hui-wen-zi-chuan-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

1254. Number of Closed Islands[DFS,BFS,并查集]

Given a 2D grid consists of 0s (land) and 1s (water). An island is a maximal 4-directionally connected group of 0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s.

Return the number of closed islands.

Example 1:

Input: grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]
Output: 2
Explanation:
Islands in gray are closed because they are completely surrounded by water (group of 1s).
Example 2:

Input: grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]
Output: 1
Example 3:

Input: grid = [[1,1,1,1,1,1,1],
[1,0,0,0,0,0,1],
[1,0,1,1,1,0,1],
[1,0,1,0,1,0,1],
[1,0,1,1,1,0,1],
[1,0,0,0,0,0,1],
[1,1,1,1,1,1,1]]
Output: 2

Constraints:

1 <= grid.length, grid[0].length <= 100
0 <= grid[i][j] <=1

DFS

class Solution {
    private int n;
    private int m;
    private boolean[][] vis;
    private int[] dx=new int[]{0,0,1,-1};
    private int[] dy=new int[]{1,-1,0,0};

    boolean isOk(int[][] grid, int x, int y){
        return x>=0&&x<n&&y>=0&&y<m&&(!vis[x][y])&&(grid[x][y]==0);
    }

    private boolean findIsland(int[][] grid, int x,int y,boolean land){
        vis[x][y]=true;

        if(x==0||x==n-1||y==0||y==m-1)land=false;

        for(int i=0;i<4;i++){
            int nx=x+dx[i];
            int ny=y+dy[i];
            if(isOk(grid,nx,ny)){
                if(findIsland(grid, nx, ny, land)==false){
                    land=false;
                };
            }
        }

        return land;
    }

    public int closedIsland(int[][] grid) {
        n=grid.length;
        m=grid[0].length;
        vis=new boolean[n][m];

        int ans=0;

        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                if(grid[i][j]==0&&!vis[i][j]){
                    //System.out.println(""+i+j);
                    if(findIsland(grid,i,j,true))ans++;
                }
            }
        }

        return ans;
    }
}

union-find

class Solution {
    int[] parent;
    boolean[] isEdge;// 是否与边缘连接

    public int closedIsland(int[][] grid) {
        int m = grid.length, n = grid[0].length;
        parent = new int[m * n];
        isEdge = new boolean[m * n];
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                int a = i * n + j;
                parent[a] = -1;
                if (grid[i][j] != 0) continue;
                parent[a] = a;
                if (i == 0 || i == m - 1 || j == 0 || j == n - 1) isEdge[a] = true;
                if (i > 0 && grid[i - 1][j] == 0) union(a, a - n);
                if (j > 0 && grid[i][j - 1] == 0) union(a, a - 1);
            }
        }
        // 统计非边缘连通块的个数
        int ans = 0;
        for (int a = 0; a < m * n; ++a) if (parent[a] == a && !isEdge[a]) ++ans;
        return ans;
    }

    int find(int a) {
        if (parent[a] == a) return a;
        return parent[a] = find(parent[a]);
    }

    void union(int a, int b) {
        int r1 = find(a), r2 = find(b);
        parent[r1] = r2;
        // 连通块里只要有一个在边缘,则此连通块与边缘连接
        isEdge[r2] |= isEdge[r1];
    }
}

作者:verygoodlee
链接:https://leetcode-cn.com/problems/number-of-closed-islands/solution/java-bing-cha-ji-by-verygoodlee-8xbb/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

45. Jump Game II【greedy】

Given an array of non-negative integers nums, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

You can assume that you can always reach the last index.

Example 1:

Input: nums = [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:

Input: nums = [2,3,0,1,4]
Output: 2

Constraints:

1 <= nums.length <= 104
0 <= nums[i] <= 1000

greedy O(n) O(n)

class Solution {
    public int jump(int[] nums) {
        int n=nums.length;
        int[] dp=new int[n];
        int l=0;
        int r=0;
        dp[0]=0;

        for(int i=1;i<n;i++)dp[i]=Integer.MAX_VALUE;

        while(l<n){
            int k=nums[l];
            for(r=Math.max(r,l+1);r<=l+k&&r<n;r++){
                dp[r]=Math.min(dp[l]+1,dp[r]);
            }
            l++;
        }
        return dp[n-1];
    }
}
  • 没想到居然能写对
  • 双指针,记录最远能到达的r,遍历l的时候,因为r之前已经被覆盖了,从l开始增加次数不会比之前的更小

greedy O(n^2) from the back to the front

class Solution {
    public int jump(int[] nums) {
        int position = nums.length - 1;
        int steps = 0;
        while (position > 0) {
            for (int i = 0; i < position; i++) {
                if (i + nums[i] >= position) {
                    position = i;
                    steps++;
                    break;
                }
            }
        }
        return steps;
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/jump-game-ii/solution/tiao-yue-you-xi-ii-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 找到离目标最远的

greedy from first to the end O(n) O(1)

class Solution {
    public int jump(int[] nums) {
        int length = nums.length;
        int end = 0;
        int maxPosition = 0; 
        int steps = 0;
        for (int i = 0; i < length - 1; i++) {
            maxPosition = Math.max(maxPosition, i + nums[i]); 
            if (i == end) {
                end = maxPosition;
                steps++;
            }
        }
        return steps;
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/jump-game-ii/solution/tiao-yue-you-xi-ii-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

加粗样式在具体的实现中,我们维护当前能够到达的最大下标位置,记为边界。我们从左到右遍历数组,到达边界时,更新边界并将跳跃次数增加 1。

在遍历数组时,我们不访问最后一个元素,这是因为在访问最后一个元素之前,我们的边界一定大于等于最后一个位置,否则就无法跳到最后一个位置了。如果访问最后一个元素,在边界正好为最后一个位置的情况下,我们会增加一次「不必要的跳跃次数」,因此我们不必访问最后一个元素。

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/jump-game-ii/solution/tiao-yue-you-xi-ii-by-leetcode-solution/
来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

更容易理解 O(n) O(1)

int jump(vector<int> &nums)
{
    int ans = 0;
    int start = 0;
    int end = 1;
    while (end < nums.size())
    {
        int maxPos = 0;
        for (int i = start; i < end; i++)
        {
            // 能跳到最远的距离
            maxPos = max(maxPos, i + nums[i]);
        }
        start = end;      // 下一次起跳点范围开始的格子
        end = maxPos + 1; // 下一次起跳点范围结束的格子
        ans++;            // 跳跃次数
    }
    return ans;
}

作者:ikaruga
链接:https://leetcode-cn.com/problems/jump-game-ii/solution/45-by-ikaruga/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

标签:return,Palindromic,int,45,len,Jump,++,length,grid
来源: https://blog.csdn.net/Wuuuuuu2019/article/details/120270069

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有