[C++] [Java] Clean Code 8 lines


  • 0

    C++

    class Solution {
    public:
        int countSubstrings(string s) {
            int cnt = 0;
            int n = s.size();
            vector<vector<bool>> isp(n, vector<bool>(n, false));
            for (int i = n - 1; i >= 0; i--) {
                for (int j = i; j < n; j++) {
                    cnt += isp[i][j] = i == j || s[i] == s[j] && (i + 1 == j || isp[i + 1][j - 1]);
                }
            }
            return cnt;
        }
    };
    

    Java

    public class Solution {
        public int countSubstrings(String s) {
            int cnt = 0;
            int n = s.length();
            char[] ca = s.toCharArray();
            boolean[][] isp = new boolean[n][n];
            for (int i = n - 1; i >= 0; i--) {
                for (int j = i; j < n; j++) {
                    cnt += (isp[i][j] = i == j || ca[i] == ca[j] && (i + 1 == j || isp[i + 1][j - 1])) ? 1 : 0;
                }
            }
            return cnt; 
        }
    }
    

  • 0

    Great work! I wrote an O(1) space c++ solution: https://discuss.leetcode.com/topic/97105/3ms-c-solution-with-o-1-space.


Log in to reply
 

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