您的位置:首页 > 编程语言 > C语言/C++

Cracking The Coding Interview 3rd -- 1.1*

2014-01-13 07:38 357 查看
Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structure?

Solution 1: 

Using additional space. There are 256 possible characters, and each character essentially is an integer. We use an array of boolean values of size 256, each element in array corresponding to each possible character. For each character, we check if it has
been visited by checking the boolean value in the array. It achieves O(1) checking time by accessing the array elements. 

The overall Time Complexity is O(n), space complexity is O(1), (an array of constant 256 elements)

Solution 2: ...

Based on the idea of Solution 1, if we further assume that there's only 'a' - 'z' characters available in input string, then we could reduce additional storage as an integer. (Haven't fully understood it yet, will add it later on)

Solution 3:

If we are allowed to alter the string, we don't need extra storage. Instead, we sort the string by characters and go through one iteration to check if there's repeats. 

The overall Time Complexity is O(nlogn) for sorting, space complexity is O(1) with in place sorting. 

Solution 4:

Brute force, nested loops. Check each character against rest of characters in string.

Time Complexity: O(n^2). Space complexity: O(1)

Header File

#ifndef __QUESTION_1_1_H_CHONG__
#define __QUESTION_1_1_H_CHONG__

#include <string>

class Question1_1 {
public:
int run();
bool isUniqueChars(const string& str);
bool isUniqueChars_2(const string& str);
string result(bool value);
};

#endif // __QUESTION_1_1_H_CHONG__


Source File

#include "stdafx.h"
#include <string>
#include <iostream>
#include "Question1_1.h"

using namespace std;

// Method 1 uses an additional 256 array of boolean values
bool Question1_1::isUniqueChars(const string& str)
{
if (str.size()>256) {
return false;
}
bool ascii_set[256] = {false};
for (int i=0; i<str.size(); ++i) {
int index = int(str[i]);
if(ascii_set[index]) {
return false;
}
ascii_set[index] = true;
}
return true;
}

// Method 2
bool Question1_1::isUniqueChars_2(const string& str)
{

}

string Question1_1::result(bool value)
{
if (value) {
return "True";
}
return "False";
}

int Question1_1::run()
{
string input[] = {"abcde", "abaa"};
for(int i=0; i<2; ++i) {
cout << input[i] << " has unique characters: " << result(isUniqueChars(input[i])) << endl;
cout << input[i] << " has unique characters: " << result(isUniqueChars_2(input[i])) << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息