zoukankan      html  css  js  c++  java
  • [LeetCode] 131. Palindrome Partitioning

    Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.

    A palindrome string is a string that reads the same backward as forward.

    Example 1:

    Input: s = "aab"
    Output: [["a","a","b"],["aa","b"]]
    

    Example 2:

    Input: s = "a"
    Output: [["a"]]

    Constraints:

    • 1 <= s.length <= 16
    • s contains only lowercase English letters.

    分割回文串。

    题意是给一个字符串,请做适当分割,使得分割的子串都是回文串。

    思路依然是回溯backtracking。

    时间O(2^n)

    空间O(n)

    Java实现

     1 class Solution {
     2     public List<List<String>> partition(String s) {
     3         List<List<String>> res = new ArrayList<>();
     4         if (s == null || s.length() == 0) {
     5             return res;
     6         }
     7         helper(res, new ArrayList<>(), s);
     8         return res;
     9     }
    10 
    11     private void helper(List<List<String>> res, List<String> list, String s) {
    12         if (s.length() == 0) {
    13             res.add(new ArrayList<>(list));
    14             return;
    15         }
    16         for (int i = 0; i < s.length(); i++) {
    17             if (isPalindrome(s.substring(0, i + 1))) {
    18                 list.add(s.substring(0, i + 1));
    19                 helper(res, list, s.substring(i + 1));
    20                 list.remove(list.size() - 1);
    21             }
    22         }
    23     }
    24 
    25     private boolean isPalindrome(String s) {
    26         for (int i = 0; i < s.length() / 2; i++) {
    27             if (s.charAt(i) != s.charAt(s.length() - i - 1)) {
    28                 return false;
    29             }
    30         }
    31         return true;
    32     }
    33 }

    LeetCode 题目总结

  • 相关阅读:
    我爱工程化 之 gulp 使用(二)
    我爱工程化 之 gulp 使用(一)
    用户体验之输入框设想
    SEO优化
    js代码优化
    RequireJs 依赖管理使用
    Git 安装与使用(一)
    Webstorm 配置与使用 Less
    Less使用——让老司机带你飞
    Node安装与环境配置
  • 原文地址:https://www.cnblogs.com/cnoodle/p/13270369.html
Copyright © 2011-2022 走看看