摘要:
2014-03-18 05:33题目:用两个栈来实现一个队列。解法:栈是反的,队列是正的,反了再反就正过来了。所以,请看代码。操作中时间复杂度有O(1)的,有O(n)的,但均摊下来时间符合O(1)。代码: 1 // 3.5 Implement a queue MyQueue using two stacks. 2 #include 3 #include 4 #include 5 #include 6 using namespace std; 7 8 template 9 class MyQueue {10 public:11 bool empty() {12 ... 阅读全文
摘要:
2014-03-18 01:45题目:给定一个NxN的矩阵,就地旋转90度。(没有样例又不说方向的话,随便往哪儿转。)解法:如果N为奇数,除了中心点以外四等分。如果N为偶数,四等分。按照A->B->C->D->A的方式,轮换赋值,需要O(1)的额外空间保存A的值。代码: 1 // 1.6 Given an image represented by an NXN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can yo 阅读全文
摘要:
2014-03-18 01:40题目:对字符串进行类似游程编码的压缩,如果压缩完了长度更长,则返回不压缩的结果。比如:aabcccccaaa->a2b1c5a3,abc->abc。解法:Count and say.代码: 1 // 1.5 Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2b1c5a3. If the compressed s 阅读全文
摘要:
2014-03-18 01:36题目:给定一个字符串,将其中的空格‘ ’替换为‘%20’,你可以认为字符串尾部有足够空间来容纳新增字符。请不要额外开辟数组完成。解法:先从前往后统计空格个数,然后从后往前填充字符,以免其他无关字符被‘%20’覆盖掉。代码: 1 // 1.4 Write a method to replace all spaces in a string with '%20'. 2 // do it in-place and backward. 3 #include 4 #include 5 using namespace std; 6 7 class Solut 阅读全文
摘要:
2014-03-18 01:32题目:对于两个字符串,判断它们是否是Anagrams。解法:统计俩单词字母构成是否相同即可。代码: 1 // 1.3 Given two strings, write a method to decide if one is a permutation of the other. 2 // count them. 3 #include 4 #include 5 using namespace std; 6 7 class Solution { 8 public: 9 bool isPermutation(const char *s, const c... 阅读全文
摘要:
2014-03-18 01:30题目:反转一个char *型的C/C++字符串。解法:一头一尾俩iterator,向中间靠拢并且交换字符。代码: 1 // 1.2 Implement a function void reverse(char *str) in C or C++ which reverses a null-terminated string. 2 #include 3 #include 4 using namespace std; 5 6 void reverse(char *str) 7 { 8 if (nullptr == str) { 9 re... 阅读全文
摘要:
2014-03-18 01:25题目:给定一个字符串,判断其中是否有重复字母。解法:对于可能有n种字符的字符集,用一个长度为n的数组统计每个字符的出现次数,大于1则表示有重复。代码: 1 // 1.1 Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structure? 2 #include 3 #include 4 using namespace std; 5 6 class Solution { 7 pub... 阅读全文