V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
hakunamatata11
V2EX  ›  推广

[leetcode/lintcode 题解] 滴滴面试题:字符删除

  •  
  •   hakunamatata11 · 2020-06-02 18:49:33 +08:00 · 857 次点击
    这是一个创建于 1449 天前的主题,其中的信息可能已经有所发展或是发生改变。

    [题目描述] 输入两个字符串,从第一字符串中删除第二个字符串中所有的字符

    在线评测地址: https://www.lintcode.com/problem/character-deletion/?utm_source=sc-v2ex-fks0602

    样例 :

    输入:  str=”They are students”,sub=”aeiou”
    输出: ”Thy r stdnts”
    

    [题解] 用一个数组储存第二串中出现过的元素,然后遍历第一数组,将未出现在第二数组中的元素保存,最后输出答案

    public class Solution {
        /**
         * @param str: The first string given
         * @param sub: The given second string
         * @return: Returns the deleted string
         */
        public String CharacterDeletion(String str, String sub) {
            int[] tmp = new int[256];
            for (int i = 0; i < sub.length(); i++) {
                tmp[sub.charAt(i)]++;
            }
            StringBuffer ans = new StringBuffer("");
            for (int i = 0; i < str.length(); i++) {
                if (tmp[str.charAt(i)] == 0) {
                    ans.append(Character.toString(str.charAt(i)));
                }
            }
            return ans.toString();
        }
    }
    

    更多语言代码参见 https://www.jiuzhang.com/solution/character-deletion/?utm_source=sc-v2ex-fks0602

    2 条回复    2020-06-03 11:26:26 +08:00
    zhoudaiyu
        1
    zhoudaiyu  
       2020-06-02 20:42:35 +08:00
    input_str = "They are students"
    sub = "aeiou"


    class Solution(object):
    @staticmethod
    def get_result(source_str, sub_str):
    return "".join(list(filter(lambda x: x not in sub_str, source_str)))

    print(Solution().get_result(input_str, sub))
    hakunamatata11
        2
    hakunamatata11  
    OP
       2020-06-03 11:26:26 +08:00
    @zhoudaiyu 👍👍👍
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1296 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 17:52 · PVG 01:52 · LAX 10:52 · JFK 13:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.