Algorithms

[알고리즘] 입력 string이 다른 입력 string의 rotation인지를 단 한번의 sub string method를 호출해서 찾기

Roien 2015. 4. 5.
반응형
#include <stdio.h>
#include <string.h>
#include <malloc.h>

//-------------------------------------------------------
// DEFINED MACRO
//-------------------------------------------------------
#define str_print(x, ...)  printf("[%04u]"x, __LINE__, ##__VA_ARGS__)


typedef unsigned int uint32;

char* append_str(char *str1, char *str2)
{
uint32 idx = 0, res_idx = 0;
uint32 len1 = strlen(str1);
uint32 len2 = strlen(str2);

char *result = (char *)malloc(len1 + len2);
if (NULL == result) {
str_print("malloc(for size %u) is failed!!", len1 + len2);
goto end;
}

for (idx = 0; idx < len1; idx++) {
result[res_idx++] = str1[idx];
}

result[res_idx] = 0;
str_print("result = %u, %s\r\n", res_idx, result);

for (idx = 0; idx < len2; idx++) {
result[res_idx++] = str2[idx];
}

result[res_idx] = 0;
str_print("result = %s\r\n", result);

end:
return result;
}


bool is_substr(char *str1, char *str2)
{
bool ret = false;
uint32 tot_len = strlen(str1);
uint32 len2 = strlen(str2);
uint32 idx = 0, equ_cnt = 0, idx_str2 = 0;

for (idx = 0; idx < tot_len; idx++) {

str_print("%c, %c, %u, %u, %u\r\n", str1[idx], str2[idx_str2], idx_str2, len2, equ_cnt);
if (idx_str2 < len2 && str1[idx] == str2[idx_str2]) {
equ_cnt++;
idx_str2++;
} else {
idx_str2 = 0;
equ_cnt = 0;
}

if (equ_cnt == len2) {
break;
}

}

if (equ_cnt == len2) {
ret = true;
}

return ret;
}


bool is_rotation(char str1[], char str2[])
{
return is_substr(append_str(str2, str2), str1);
}


int main(void)
{
char *tgt_str = "terwa";
char *src_str = "water";
bool ret = is_rotation(tgt_str, src_str);
printf("%s is a substring of %s ? %s", (char *)tgt_str, (char *)src_str, (true == ret ? "true":"false"));
return 0;
}


반응형

댓글