zoukankan      html  css  js  c++  java
  • 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);
        }
  • 相关阅读:
    PyQt(Python+Qt)学习随笔:containers容器类部件QStackedWidget重要方法介绍
    什么叫工业4.0,这篇接地气的文章终于讲懂了
    怎样 真正认识一个 人
    华为的绩效管理:减人、增 效、加薪
    羽毛球战术
    魔方教程
    员工培养:事前指导,事后纠正
    一把手瞄准哪里,核心竞争力就在哪里
    海尔的五次战略变革
    如何提高基层员工的执行力
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8721195.html
Copyright © 2011-2022 走看看