LeetCode //C - 1332. Remove Palindromic Subsequences

1332. Remove Palindromic Subsequences

You are given a string s consisting only of letters 'a' and 'b'. In a single step you can remove one palindromic subsequence from s.

Return the minimum number of steps to make the given string empty.

A string is a subsequence of a given string if it is generated by deleting some characters of a given string without changing its order. Note that a subsequence does not necessarily need to be contiguous.

A string is called palindrome if is one that reads the same backward as well as forward.

Example 1:

Input: s = "ababa"

Output: 1

Explanation: s is already a palindrome, so its entirety can be removed in a single step.

Example 2:

Input: s = "abb"

Output: 2

Explanation: "abb" -> "bb" -> "".

Remove palindromic subsequence "a" then "bb".

Example 3:

Input: s = "baabb"

Output: 2

Explanation: "baabb" -> "b" -> "".

Remove palindromic subsequence "baab" then "b".

Constraints:
  • 1 <= s.length <= 1000
  • si is either 'a' or 'b'.

From: LeetCode

Link: 1332. Remove Palindromic Subsequences


Solution:

Ideas:

Since s contains only 'a' and 'b':

  • If s is already a palindrome, remove the entire string in 1 step.
  • Otherwise, remove all 'a' characters as one palindromic subsequence, then all 'b' characters as another. Therefore, the answer is 2 steps.
Code:
c 复制代码
#include <string.h>

int removePalindromeSub(char* s) {
    int left = 0;
    int right = strlen(s) - 1;

    while (left < right) {
        if (s[left] != s[right]) {
            return 2;
        }

        left++;
        right--;
    }

    return 1;
}
相关推荐
Code_Solitude13 分钟前
c语言:期末复习(7)
c语言·开发语言·算法
金榜题名萱24 分钟前
蓝桥杯 - 旗帜
c语言·数据结构·c++·算法·蓝桥杯
jianqiang.xue1 小时前
GCC 15 还是 ST-ARM-Clang:STM32 的 VS Code 工具链怎么定
c语言·arm开发·stm32·嵌入式硬件·嵌入式·ai编程·代码审查
Rain的Java大神之路1 小时前
LeetCode 46 全排列:从「及格答案」到让面试官眼前一亮的三种写法
后端·leetcode·面试
程序员与背包客_CoderZ1 小时前
Linux C++异步网络编程:c-ares高性能DNS解析编码实战
linux·服务器·c语言·开发语言·网络·c++·网络编程
LabVIEW开发2 小时前
探测器脉冲只有 500 ns,谱线要分 2048 道:LabVIEW 怎么把振动台和计数器锁在同一根时间轴上
人工智能·算法·labview
小O的算法实验室2 小时前
SEVC,面向拥塞感知的无人机-卡车协同路径规划的深度强化学习框架
算法
醉颜凉2 小时前
区块链不可篡改机制全解析:从哈希锁链到51%攻击
算法·区块链·哈希算法