Leetcode初級アルゴリズム文字列C言語解答
37645 ワード
Leetcode初級アルゴリズム文字列C言語解答
344.文字列の反転
344.文字列の反転
void reverseString(char* s, int sSize) {
int temp, i, j = sSize-1;
for(i=0; i<j; i++, j--){
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
return s;
}
7.整数反転
7.整数反転
int reverse(int x) {
int pop, rev = 0;
while (x != 0) {
pop = x % 10;
x /= 10;
if (rev > INT_MAX/10 || (rev == INT_MAX / 10 && pop > 7))
return 0;
if (rev < INT_MIN/10 || (rev == INT_MIN / 10 && pop < -8))
return 0;
rev = rev * 10 + pop;
}
return rev;
}
387.文字列の最初の一意の文字
387.文字列の最初の一意の文字
int firstUniqChar(char* s) {
int d[26]={0};
int temp, i;
for(i=0; s[i]!='\0'; i++){
temp = s[i] - 'a';
d[temp]++;
}
for(i=0; s[i]!='\0'; i++){
temp = s[i] - 'a';
if(d[temp] == 1)
return i;
}
return -1;
}
242.有効なアルファベット異位語
242.有効なアルファベット異位語
bool isAnagram(char* s, char* t) {
int i, x[26] = { 0 }, y[26] = { 0 };
for (i = 0; s[i] != '\0'; i++)
x[s[i] - 'a']++;
for (i = 0; t[i] != '\0'; i++)
y[t[i] - 'a']++;
for (i = 0; i < 26; i++)
if (x[i] != y[i])
return false;
return true;
}
125.検証文字列
125.検証文字列
bool isPalindrome(char* s) {
size_t i = 0;
size_t j = strlen(s);
while(i < j)
if(s[i] < '0' || (s[i] > '9' && s[i] < 'A') || (s[i] > 'Z' && s[i] < 'a') || s[i] > 'z')
i++;
else if(s[j] < '0' || (s[j] > '9' && s[j] < 'A') || (s[j] > 'Z' && s[j] < 'a') || s[j] > 'z')
j--;
else
if (tolower(s[i]) != tolower(s[j])){
return false;
}
else{
i++;
j--;
}
return true;
}
8.文字列変換整数(atoi)
8.文字列変換整数(atoi)
int myAtoi(char* str) {
int i=0, flag=1;
while (str[i]==' ')
i++;
if (str[i] == '-'){
flag=-1;
i++;
}
else if (str[i] == '+')
i++;
double temp = 0;
while (str[i] != '\0'){
if(str[i]<'0'||str[i]>'9')
break;
else
temp = temp*10+str[i]-'0';
i++;
}
if (temp > INT_MAX)
if(flag==-1)
return INT_MIN;
else
return INT_MAX;
else
return temp * flag;
}
28.strStr()の実装
28.strStr()の実装
int strStr(char* haystack, char* needle) {
if(*needle=='\0')
return 0;
else if(*haystack=='\0')
return -1;
int a_len=strlen(haystack),b_len=strlen(needle),i=0,j=0;
if(a_len<b_len)
return -1;
for(i=0;i<=a_len-b_len;i++){
for(j=0;j<b_len;j++){
if(*(haystack+i+j)==*(needle+j))
continue;
else
break;
}
if(j==b_len && *(haystack+i+j-1)==*(needle+j-1))
return i;
}
return -1;
}
int strStr(char* haystack, char* needle) {
if(*needle=='\0')
return 0;
else if(*haystack=='\0')
return -1;
int nlen = strlen(needle);
int* next[nlen];
cal_next(needle, next);
return KMP(haystack, needle, next);
}
void cal_next(char* str, int* next){
int i, j;
int len = strlen(str);
next[0] = -1;
for(i = 1; i < len; i++){
j = next[i - 1];
while(str[j + 1] != str[i] && (j >= 0))
j = next[j];
if( str[i] == str[j + 1])
next[i] = j + 1;
else
next[i] = -1;
}
}
int KMP( char * str, char * ptr, int * next ){
int s_i = 0, p_i = 0;
int plen = strlen(ptr);
int slen = strlen(str);
while( s_i < slen && p_i < plen ){
if( str[ s_i ] == ptr[ p_i ] ){
s_i++;
p_i++;
}
else{
if( p_i == 0 )
s_i++;
else
p_i = next[ p_i - 1 ] + 1;
}
}
return ( p_i == plen ) ? ( s_i - plen ) : -1;
}