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

2020-06-02 18:49:33 +08:00
 hakunamatata11

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

在线评测地址: 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

859 次点击
所在节点    推广
2 条回复
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
2020-06-03 11:26:26 +08:00
@zhoudaiyu 👍👍👍

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/677965

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX