Leetcode PHP题解--D70 784. Letter Case Permutation


D70 784. Letter Case Permutation

题目链接

784. Letter Case Permutation

题目分析

给定一个字符串。返回将其字母部分替换成大小写分别可能出现的所有字符。

例如,字符串为a时,返回aA
字符串为Ab时,返回['Ab','AB','ab','aB']

思路

先找到字符串中字母出现的位置。

对于每个出现字母的位置,将小写和大写两种字符串都存进新数组里。

对新数组进行去重和排序,并返回。

最终代码

<?php
class Solution {

    /**
     * @param String $S
     * @return String[]
     */
    function letterCasePermutation($S) {
        $all = [$S];
        $S = str_split($S);
        $alphabets = str_split('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
        $chars = array_intersect($S, $alphabets);
        foreach($chars as $key => $value){
            foreach($all as $newString){
                $newStringArray = str_split($newString);
                $newStringArray[$key] = strtolower($newStringArray[$key]);
                $all[] = implode($newStringArray);

                $newStringArray = str_split($newString);
                $newStringArray[$key] = strtoupper($newStringArray[$key]);
                $all[] = implode($newStringArray);
            }
        }
        $all = array_unique($all);
        sort($all);
        return $all;
    }
}

若觉得本文章对你有用,欢迎用爱发电资助。


点赞 取消点赞 收藏 取消收藏

<< 上一篇: Leetcode PHP题解--D69 258. Add Digits

>> 下一篇: Leetcode PHP题解--D71 788. Rotated Digits