Java 28ms Solution


  • 1
    C
    public class Solution {
        public int findMaxForm(String[] strs, int m, int n) {
            int[][] dp = new int[m+1][n+1];
            for (int s = strs.length-1; s>=0;s--) 
            {
                int[] count = count(strs[s]);
                for (int i=m;i>=count[0];i--) 
                    for (int j=n;j>=count[1];j--) 
                        dp[i][j] = Math.max(1 + dp[i-count[0]][j-count[1]], dp[i][j]);
                           
            }
            return dp[m][n];
        }
        public int[] count(String str) {
            int[] res = new int[]{0,0};
            for (int i=0;i<str.length();i++){
                if(str.charAt(i)=='0') res[0]++;
                else res[1]++;
            }
            return res;
         }
    }
    

  • 0
    M

    You could also count ones and zeros like so:

    res[0] = str.replaceAll("1", "").length(); //just the zeros
    res[1] = str.replaceAll("0", "").length(); //just the ones
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.