complementary tutorial 2 – strings++
DESCRIPTION
Complementary tutorial 2 – strings++. Prepared by: Valentin Kravtsov. char str[] = "abcdefghkl"; int i,str_len = strlen(str); for(i=0 ; iTRANSCRIPT
Complementary tutorial 2 – strings++
Prepared by: Valentin Kravtsov
Given a string, reverse it
char str[] = "abcdefghkl";
int i,str_len = strlen(str);
for(i=0 ; i<str_len/2 ; i++){
swap(str+i , str+str_len – 1 – i );
}
Output: lkhgfedcba
Given string of size n, rotate it m places to the right: No new arrays are allowed. O(nm)
abcdefghk => fghkabcde (n=9, m=4).
char tmp,str[] = "abcdefghk";
int i,j, m=4, n = strlen(str);
for(i=0;i<m;i++){
tmp = str[n-1];
for(j=n-2;j>=0;j--) { str[j+1] = str[j]; }
str[0] = tmp;
}
Output: fghkabcde
Given string of size n, rotate it m places to the right: (n=9, m=4). The efficient version. O(n)
abcdefghk => fghkabcde
The algorithm:
1. Identify the new first letter: “f”
2. Reverse both parts: edcbakhgf
3. Reverse the entire string: fghkabcde
The code:
void reverse(char* str, int from, int to){ int i, half_len = (to-from+1)/2; for(i=0;i<half_len;i++){ swap(str+from+i, str+to-i); } }
char str[] = "abcdefghk";int i, m=4, n = strlen(str), break_point = n-m; reverse(str,0,break_point-1);reverse(str,break_point,n-1);reverse(str,0,n-1);
Output: fghkabcde
Given string of with several words, reverse the order of words, (not characters), no additional arrays/strings are allowed. O(n)
ima aba and bamba => bamba and aba ima
The algorithm:
1. Reverse the whole string:
abmab dna aba ami
2. Reverse the letters in each word:
bamba and aba ima
Given string of with several words, reverse the order of words, (not characters), no additional arrays/strings are allowed.
ima aba and bamba => bamba and aba ima
char tmp,str[] = "ima aba and bamba";int end,start=0, n = strlen(str); reverse(str,0,n-1);while( find_next_word(str,&start,&end) ){ reverse(str,start,end); start=end+1; }
int find_next_word(char* str, int* start, int* end){
for( ; str[*start] && str[*start]==' '; (*start)++){}
if( !str[*start] ) return 0;
for(*end = *start ; str[*end+1] &&
str[*end+1] !=' ' ; (*end)++){}
return 1;
}
Finds next word by updating start and end to appropriate values. Return true/false (1/0) if a new word is found.
Compile/not compile questions
Compile/not compile questions
Compile/not compile questions
Compile/not compile questions
Given an array of characters of size n, and a new “order”, find if it is “newly ordered”.
Your very challenging homework…
Given an array of integers of size n, where one number appears more then n/2 times. Find this number, by scanning the array one time only.