LeetCode-Letter Case Permutation

本文介绍了一种通过递归和回溯实现字符串中字母任意大小写变换的算法,旨在生成给定字符串的所有可能形式,适用于长度1到12的字符串,包含字母和数字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description:
Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create.

Examples:

Input: S = "a1b2"
Output: ["a1b2", "a1B2", "A1b2", "A1B2"]

Input: S = "3z4"
Output: ["3z4", "3Z4"]

Input: S = "12345"
Output: ["12345"]

Note:

  • S will be a string with length between 1 and 12.
  • S will consist only of letters or digits.

题意:给定一个字符串,对其中的字母进行任意数量的大小写转换,要求返回所有可能的结果;

解法:很容易想到可以利用递归和回溯来解决这个问题;用index记录当前字符串的遍历位置,我们每次从当前位置遍历字符串,找到第一个出现的字母,将其进行大小写的转换得到一个新的字符串temp(temp就是结果种的一种可能),之后可以再对字符串temp利用上面的方法重新找到第一个出现字母的位置又可以得到一个新的字符串,直到index超出了字符串的长度后我们可以执行回溯,返回最近一次修改字母大小写的位置处,不执行修改直接执行上述的操作;

Java
class Solution {
    public List<String> letterCasePermutation(String S) {
        List<String> result = new ArrayList<>();
        result.add(S);
        permutation(result, S, 0);
        return result;
    }
    private void permutation(List<String> result, String S, int index) {
        if (index >= S.length()) return;
        for (int i = index; i < S.length(); i++) {
            char ch = S.charAt(i);
            String temp = "";
            if (!Character.isLetter(ch)) continue;
            if (Character.isLowerCase(ch)) {
                temp = S.substring(0, i) + Character.toUpperCase(ch) + S.substring(i+1);
            } else {
                temp = S.substring(0, i) + Character.toLowerCase(ch) + S.substring(i+1);
            }
            result.add(temp);
            permutation(result, temp, i+1);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值