Q. 156: Binary Tree Upside Down
Given a binary tree
{1,2,3,4,5}
,
1 / \ 2 3 / \ 4 5
[4,5,2,#,#,3,1]
.
4 / \ 5 2 / \ 3 1
<span style="color:#333333;">TreeNode *upsideDownBinaryTree(TreeNode *root) {
TreeNode *new_root = NULL;
buildUpsideDownBT(root, new_root);
return new_root;
}
TreeNode *buildTree(TreeNode *root, TreeNode* &new_root) {
if(!root) return root;
if(!root->left && !root->right) {
new_root = root;
return root;
}
TreeNode *parent = buildTree(root->left, new_root);
parent->left = root->right;
parent->right = root;
root->left = root->right = NULL; //very important
return parent->right;
}
Q. 157: Read N Characters Given Read4
int read4(char *buf)
reads 4 characters at a time from a file.
read4
API, implement the function
int read(char *buf, int n)
that reads
n characters from the file.
C++实现如下:
int read4(char* buff);
int read(char* buff, int n){
int total_len = 0;
int curr_len = 0;
while(total_len+4<=n){
curr_len = read4(buff+total_len);
total_len += curr_len;
if(curr_len<4) break;
}
if(curr_len<4 && total_len==n) return total_len;
char* new_buff = new char[5];
curr_len = read4(new_buff);
curr_len = min(curr_len, n-total_len);
for(int i=0; i<curr_len; ++i) buff[total_len+i] = new_buff[i];
delete new_buff;
return total_len+curr_len;
}
Q. 158: Read N Characters Given Read4 II - Call multiple times
The API: int read4(char *buf)
reads 4 characters at a time from a file.
The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.
By using the read4
API, implement the function int read(char *buf, int n)
that reads n characters from the file.
分析: 注意这个可以读多次,如果buffer有剩余,下次要从剩下的地方读取.
C++实现如下:
int read(char* buff, int n){
int total_len = 0;
static int curr_len = 4;
static char* local_buff = new char[5];
static int local_p = 4;
while(total_len<n){
if(local_p==curr_len)
{
if(curr_len<4) break;
curr_len = read4(local_buff);
local_p = 0;
}
if(local_p < curr_len) buff[total_len++] = local_buff[local_p++];
}
return total_len;
}
Q. 159: Longest Substring with At Most Two Distinct Characters
Given a string, find the length of the longest substring T that contains at most 2 distinct characters.
For example, Given s = “eceba”
, T is "ece"
which its length is 3.
int longestSubstring(const string& s, const int n){
int hash[128];
memset(hash, 0, sizeof(int)*128);
int left = 0;
int right = 0;
int k = 0; //number of distinct character
int max_len = 0;
while(right<s.size()){
++hash[s[right]];
if(hash[s[right]]==1) ++k;
++right;
while(k>n){
--hash[s[left]];
if(hash[s[left]]==0) --k;
++left;
}
if(max_len<right-left) max_len = right - left;
cout << left << ", " << right << ", " << k << endl;
}
return max_len;
}
Q. 161: One Edit Distance
Given two strings S and T, determine if they are both one edit distance apart.
Hint:
1. If | n – m | is greater than 1, we know immediately both are not one-edit distance apart.
2. It might help if you consider these cases separately, m == n and m ≠ n.
3. Assume that m is always ≤ n, which greatly simplifies the conditional statements. If m > n, we could just simply swap S and T.
4. If m == n, it becomes finding if there is exactly one modified operation. If m ≠ n, you do not have to consider the delete operation. Just consider the insert operation in T.
分析: For one edit distance, there are two qualified cases. Case 1 is that S.length equals T.length, so we just find out that if there is only one different character between S and T. Case 2 is that T is one character longer than S, except that different character, all other characters are the same.
Java实现如下:
public boolean isOneEditDistance(String s, String t) {
int lenS = s.length(), lenT = t.length();
//if s is longer than t, switch them.
//then we can make sure that t is always
//longer than s.
if (lenS > lenT)
return isOneEditDistance(t, s);
//if the length difference is larger than 1,
//obviously the edit distance cannot be 1
int lengthDiff = lenT - lenS;
if (lengthDiff > 1)
return false;
//iterate though shorter string s, find the first
//different char between s and t.
int i = 0;
while (i < lenS && s.charAt(i) == t.charAt(i))
i++;
//when i equals lenS, there are two possibilities
//one is that s equals t(lengthDiff = 0), return false;
//otherwise it is the one edit distance, return true.
if (i == lenS)
return lengthDiff > 0;
//case: bcd, ccd
//case 1 that i stops in the middle or beginning of s,
//skip this different character.
if (lengthDiff == 0)
i++;
//skip the different character in longer string t. case: bcd, ccde
while (i < lenS && s.charAt(i) == t.charAt(i + lengthDiff))
i++;
return i == lenS;
}
Q.163: Missing Ranges
C++实现如下:
vector<string> missingRanges(const vector<int>& nums, int start, int end){
int missing = start;
vector<string> result;
for(int i=0; i<nums.size(); ++i){
if(missing<nums[i]){
string s = to_string(missing);
if(missing<nums[i]-1){
s += "->";
s += to_string(nums[i]-1);
}
result.push_back(s);
missing = nums[i]+1;
}
else ++missing;
}
if(missing<=end){
string s = to_string(missing);
if(missing<end){
s += "->";
s += to_string(end);
}
result.push_back(s);
}
return result;
}
Q.167: Two Sum II - Input array is sorted
C++实现如下:
pair<int, int> twoSum(const vector<int>& nums, int target){
int left = 0;
int right = nums.size()-1;
while(left<right){
if(nums[left]+nums[right]<target) ++left;
else if(nums[left]+nums[right]>target) --right;
else break;
}
return make_pair(left, right);
}
Q. 170: Two Sum III - Data structure design
add
and
find
.
add
- Add the number to an internal data structure.
find
- Find if there exists any pair of numbers which sum is equal to the value.
add(1); add(3); add(5); find(4) -> true find(7) -> false
class TwoSum{
unordered_map<int, int> hash;
public:
void add(int number){
++hash[number];
}
bool find(int target){
for(unordered_map<int, int>::iterator it=hash.begin(); it!=hash.end(); ++it){
if(hash.count(target - it->first)){
if(target != it->first*2) return true;
else if(hash[it->first]>1) return true;
}
}
return false;
}
};
Q. 186: Reverse Words in a String II
Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces and the words are always separated by a single space.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Could you do it in-place without allocating extra space?
C++实现如下:
string reverseWords(string s){
reverse(s.begin(), s.end());
size_t start = 0;
size_t end = s.find(' ');
while(end!=string::npos){
reverse(s.begin()+start, s.begin()+end);
start = end+1;
end = s.find(' ', start);
}
reverse(s.begin()+start, s.end());
return s;
}