Category Archives: Arrays and Strings
Longest palindrome substring
Compute Adjacent pair
Min in Array
Merge Array
Palindrome Integer
Set Matix Zero
Rotated Matrix
/***
Given an image represented by an N*N matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?
int – 4bytes
***/
/***
complexity O(N2)
a[i][j] -> a[j][sz-1-i]
a[j][sz-1-i] -> a[sz-1-i][sz-1-j]
a[sz-1-i][sz-1-j] -> a[sz-1-j][i]
a[sz-1-j][i] -> a[i][j]
(0,0) -> (0,n)
(0,n) -> (n,n)
(n,n) -> (n,0)
(n,0) -> (0,0)
trick: inner loop should be looped less than size..to avoid double rotate for the edge
***/
#include
using namespace std;
void rotate90(int (*a)[4], int sz) {
int temp;
for(int i = 0; i < sz/2; i++) {
for(int j = i; j < sz-2*i-1; j++) {
temp = a[i][j];
a[i][j] = a[sz-1-j][i];
a[sz-1-j][i] = a[sz-1-i][sz-1-j];
a[sz-1-i][sz-1-j] = a[j][sz-1-i];
a[j][sz-1-i] = temp;
}
}
}
void print(int (*a)[4], int sz) {
for(int i=0; i<sz; i++) {
for(int j=0; j<sz; j++)
cout<<a[i][j]<<" ";
cout<<endl;
}
}
void main () {
int a[][4] = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,16}};
print(a, 4);
cout<<endl;
rotate90(a, 4);
print(a, 4);
}
Replace String
/***
Write a method to replace all spaces in a string with ‘%20’. You may assume that
the string has sufficient space at the end of the string to hold the additional
characters and that you are given the “true” length of the string.
***/
#include
#include
using namespace std;
void replaceString(string *str) {
string::iterator it;
string str1 = “%20”;
for(it = str->begin(); it != str->end(); it++) {
if(*it == ‘ ‘) {
str->replace(it, it+1, str1);
}
}
}
Test
void main() {
string str = “Xiang is a joke.”;
replaceString(&str);
cout<<str<<endl;
}
is Permutation
***
Given two strings, write a method to decide if one is a permutation of the other.
***/
/***
1. if size is different, return false.
2. next_permutation, chk..
***/
#include
#include
#include
using namespace std;
bool isPermutation(string *str1, string *str2) {
if (str1->size() != str2->size()) return false;
do {
if(*str1 == *str2)
return true;
} while(next_permutation(str2->begin(), str2->end()));
return false;
}
Test
void main() {
string str1 = “happy”;
string str2 = “ahppy”;
if (isPermutation(&str1, &str2))
{
cout<<"yes"<<endl;
} else cout<<"no"<<endl;
}