Cracking The Coding Interview 3rd -- 1.1*

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;
}







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值