[daily coding] longest palindromic continuous substring

임택·2021년 3월 7일
0

알고리즘

목록 보기
49/63

problem

code

abba => bb is palindromic. for (x)bb(y), x == y then, it is palindromic

1st try:

var solution = s => {
  const len = s.length;
  let ans = s.substring(0, 1);
  if (len <= 1) return s;
  
  let memo = [];
  console.log(memo);

  for (let i = 0; i < len; i++) {
    	memo[i] = memo[i] || []
        memo[i][i] = true; // length 1
    	
    	// length 2
    	if (i + 1 < len && s.charAt(i) == s.charAt(i + 1)) {
			memo[i][i + 1] = true;
          	ans = s.substring(i, i + 1 + 1);
        }
  }
  console.log(memo);
  
  // from length 3 to len
  for (let i = 2; i < len; i++) {
  	for (let j = 0; j + i < len; j++) {
		if (memo[j + 1][j + i - 1]) {
        	if (s.charAt(j) == s.charAt(j + i)) {
            	memo[j][j+i] = true;
              	if (ans.length < i + 1)
              	ans = s.substring(j, j + i + 1);
            }
        }
    }
  }
  console.log(memo);
  
  
  return ans;
}
var arr = ['a', '', 'aabb', 'abba', 'aabbccc', 'abababcbcbcb'];
for (const s of arr)
	console.log(solution(s));

Time: O(N^2)
Space: O(N^2)

profile
캬-!

0개의 댓글