【Cracking the coding interview】Q1.3(移除重复字符)
2013-12-23 19:18
423 查看
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.
设计算法并写出代码移除字符串中重复的字符,不能使用额外的缓存空间。注意: 可以使用额外的一个或两个变量,但不允许额外再开一个数组拷贝。
进一步地,为你的程序写测试用例。
思路,类似Q1.1 用一个bool辅助数组来做
FOLLOW UP
Write the test cases for this method.
设计算法并写出代码移除字符串中重复的字符,不能使用额外的缓存空间。注意: 可以使用额外的一个或两个变量,但不允许额外再开一个数组拷贝。
进一步地,为你的程序写测试用例。
思路,类似Q1.1 用一个bool辅助数组来做
#include<iostream> #include<cstring> #include<stdlib.h> using namespace std; //char s[]数组 void removeduplicate(char s[]){ bool check[256]; memset(check, false, sizeof(check));//这句很重要 int p=0,i=0; int len=strlen(s); while(i<len){ if(!check[s[i]]){ s[p++]=s[i]; check[s[i]]=true; } i++; } s[p]='\0'; } //string string removeduplicatestring(string s){ int len=s.length(); if(len<2) return s; int check=0,i=0; string str=""; while(i<len){ if(!(check&(1<<(s[i]-'a')))){ str +=s[i]; check |=1<<(s[i]-'a'); } i++; } return str; } int main(){ char s[]="1dadf"; removeduplicate(s); cout<<s<<endl; string s2="abcdeaf"; cout<<removeduplicatestring(s2); system("pause"); return 0; }
相关文章推荐
- Cracking the coding interview--Q1.3
- 【Cracking the coding interview】Q1.1(字符唯一)
- Cracking the coding interview--Q1.3
- Cracking the coding interview--Q1.3
- Cracking the coding interview--Q1.3
- Cracking the coding interview--Q1.3
- Cracking the coding interview--Q1.3
- Cracking coding interview(1.3)去掉字符串中重复字符
- Cracking the coding interview--Q9.1
- Cracking the coding interview--Q3.2
- Cracking the coding interview--Q19.5
- Cracking the coding interview--Q1.8
- Cracking the coding interview(原版)
- 《Cracking the Coding Interview》——第8章:面向对象设计——题目4
- Cracking the coding interview--Q8.2
- 《Cracking the Coding Interview》——第10章:可扩展性和存储空间限制——题目1
- 《Cracking the Coding Interview》——第12章:测试——题目5·
- Cracking the coding interview--Q3.2
- 《Cracking the Coding Interview》——第13章:C和C++——题目2
- Cracking the coding interview--Q20.11