Cracking the coding interview--Q1.3

题目

原文:

Design an algorithm and write code to remove the duplicate characters in a string without using any additional buffer. NOTE: One or two additional variables are fine. An extra copy of the array is not.

FOLLOW UP

Write the test cases for this method.

译文:

设计算法并写出代码移除字符串中重复的字符,不能使用额外的缓存空间。注意: 可以使用额外的一个或两个变量,但不允许额外再开一个数组拷贝。

进一步地,

为你的程序写测试用例。

解答

这道题目其实是要你就地(in place)将字符串中重复字符移除。你可以向面试官问清楚, 不能使用额外的一份数组拷贝是指根本就不允许开一个数组,还是说可以开一个固定大小, 与问题规模(即字符串长度)无关的数组。

如果根本就不允许你再开一个数组,只能用额外的一到两个变量。那么,你可以依次访问 这个数组的每个元素,每访问一个,就将该元素到字符串结尾的元素中相同的元素去掉( 比如置为'').时间复杂度为O(n2 ),代码如下:

java

package cha1;

public class A003 {
    
    public static char[] rmDuplicate(char[] cs) {
        int p = 0;
        for (int i=0; i<cs.length; i++) {
            if (cs[i] != ''){
                cs[p++] = cs[i];
                for(int j=i+1; j<cs.length; j++) {
                    if (cs[i] == cs[j]) {
                        cs[j] = '';
                    }
                }
            }
        }
        for (; p<cs.length; p++)
            cs[p] = '';
        return cs;
    }
    
    public static void main(String[] args) {
        char[] cs = {'l','o','u','l','l','5','2','6','l','o','u','k'};
        char[] ss = new char[4];
        ss[2] = 'l';
        for (char c : ss) {
            System.out.println(c);
        }
        System.out.println(rmDuplicate(cs));
    }
}
原文地址:https://www.cnblogs.com/549294286/p/3190759.html