• LF.395.Remove Certain Characters


    Remove given characters in input string, the relative order of other characters should be remained. Return the new string after deletion.

    Assumptions

    The given input string is not null.
    The characters to be removed is given by another string, it is guranteed to be not null.
    Examples

    input = "abcd", t = "ab", delete all instances of 'a' and 'b', the result is "cd".


    time: o(n) space o(n)
    public String remove(String input, String t) {
            // Write your solution here
            char[] inputs = input.toCharArray() ;
            char[] ts = t.toCharArray() ;
            //put all the ts input hashset
            Set<Character> set = new HashSet<>(ts.length) ;
            StringBuilder sb = new StringBuilder() ;
            for (int i = 0; i < ts.length; i++) {
                set.add(ts[i]);
            }
            for (int i = 0; i <inputs.length ; i++) {
                if (!set.contains(inputs[i])){
                    sb.append(inputs[i]);
                }
            }
            return sb.toString();
        }
        //another method using two pointers: valid area: [0, slow)
        public String remove_twopointer(String input, String t) {
            // Write your solution here
            int slow = 0, fast = 0 ;
            //put the t into hashset
            Set<Character> set = new HashSet<>(t.length());
            char[] inputs = input.toCharArray() ;
            for (int k = 0; k < t.length(); k++) {
                set.add(t.charAt(k));
            }
            //only need to check the fast
            /*          d
            *       s t u d
            *       i i i-i
            *       j j j j j
    String
    public String(char[] value,
                  int offset,
                  int count)
    Allocates a new String that contains characters from a subarray of the character array argument.
    The offset argument is the index of the first character of the subarray and the count argument specifies the length of the subarray.
    The contents of the subarray are copied;
    subsequent modification of the character array does not affect the newly created string.
    
    Parameters:
    value - Array that is the source of characters
    offset - The initial offset
    count - The length
    
            * */
            while (fast<input.length()){
                if (set.contains(input.charAt(fast))){
                    fast++ ;
                } else{
                    inputs[slow++] = inputs[fast++] ;
                }
            }
            return new String(inputs, 0, slow);
        }
  • 相关阅读:
    coding 绑定 ssh 公钥后 还报没有权限???
    定位方法 xpath,css
    css 定位方法
    pyse
    kafka自动安装脚本systemctl服务
    Visual Studio Code(VS Code)插件
    2022最新web前端面试题分享pdf 170页
    浏览器缓存机制介绍与缓存策略剖析
    前端性能优化攻略
    linux中用wget下载整个网页以及子网页
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8721195.html
Copyright © 2020-2023  润新知