2016-12-17 3 views
0

현재 주어진 문자열에 palindroms 단어가 몇 개 있는지 확인하고 해당 번호를 main으로 반환하는 함수를 작성하려고합니다. 내 접근 방식은 문자열의 길이를 확인하고 역순으로 다른 문자열로 복사 한 다음 둘 다 비교하는 것이 었습니다. 내가 빈 공간을 도달 할 때마다 확인하면서문자열 palindrom 검사

#define _CRT_SECURE_NO_WARNINGS 
#include <stdio.h> 
#include <string.h> 

int palindrom(char str1[81]); 

int main(){ 

    char str[81]; 
    gets(str); 
    printf("%d pali\n", palindrom(str)); 


} 


int palindrom(char str[81]) { 

    int i, j=0, k = 0, pali_count = 0, length = 0, flag=0; 
    char rev[81], c; 
    for (i = 0; str[i] != '\0'; i++){}//getting the string length 

    while (i >= 0) {//revrsing the string 
     rev[j++] = str[--i]; 
    } 
    rev[j-1] = '\0'; 
    printf("%s", rev); 


    length = j - 2; 
    k = length; 
    j = 0; 
    while (k >= 0) { 
     k--; 
     j++; 
     c = rev[k]; 
     if (rev[k] != str[j]) 
      flag++; 
     if (c == ' ') { 
      if (flag == 0) 
       pali_count++; 
      flag = 0; 
      continue; 
     } 

     return pali_count; 

    } 





    return 0; 

} 
+3

및 질문/문제는 무엇인가? – Derlin

+0

괜찮지 만 질문이 뭐니 뭐니 뭐니 뭐니해도 문제가 어디 있니? –

+0

나는 정확한 숫자의 회문을 얻지 못한다고 생각한다. –

답변

1

코드에서 실수를 많이 있습니다. 내가 당신에게 하나 하나 설명하자 : while loop에서

  • 을 (당신이 현재의 문자열을 역 문자열을 확인할 경우) 당신은 항상 제로 한 반복 한 후 pali_count을 반환합니다.
  • 마지막 단어가 회문 단어 인 경우 마지막 단어에 공백이 없기 때문에 회문으로 사용할 수 없습니다.
  • 마지막으로 전체 알고리즘이 잘못되었습니다. 이 될 것입니다 단어를 반전 후

    가정 STR = 'sabuj'

    : 아래의 예를 확인 레브 = 'jubas'지금은 모든 첫 번째 문자와 마지막 문자를 확인하면

    char는 동일하므로 잘못된 결과를줍니다. 먼저 문자열을 뒤집어서 처음 숯을 첫 번째 숯으로 확인해야합니다.

    mahedi sabuj과 같은 문장의 경우 또 다른 문제가 발생합니다.이 단어는 jubas ideham으로 확인됩니다.이 단어는 첫 번째 단어를 두 번째 단어와 일치시키고 그 반대도 마찬가지이기 때문에 잘못되었습니다.

이제 여기에 솔루션입니다 : space

  • 는 각 단어가 회문
  • 입니다 걸릴과

    • 분할 문장 예

    여기에 수를 늘리면 코드는

    입니다.
    #define _CRT_SECURE_NO_WARNINGS 
    #include <stdio.h> 
    #include <string.h> 
    
    int palindrom(char str1[81]); 
    
    int main(){ 
    
        char str[81]; 
        gets(str); 
    
        int result = 0; 
    
        char *p = strtok(str, " "); // split word by space 
    
        while(p != NULL) 
        { 
         result += palindrom(p); 
         p = strtok(NULL, " "); 
        } 
    
    
        printf("%d pali\n", result); 
    } 
    
    
    int palindrom(char str[81]) 
    { 
    
        int i, j=0, k = 0, pali_count = 0, length = 0, flag=0; 
        char rev[81], c; 
    
        for (i = 0; str[i] != '\0'; i++){} //getting the string length 
    
        while (i >= 0) //revrsing the string 
        { 
         rev[j++] = str[--i]; 
        } 
    
        rev[j-1] = '\0'; 
    
        length = j - 2; 
        k = length; 
        j = length; 
    
        while (k >= 0) 
        { 
         if (str[j] != rev[k]) 
         return 0; 
    
         k--; 
         j--; 
        } 
    
        return 1; 
    } 
    

    샘플 I/O :

    부인의 mm의 sabuj -> 2 팔리어

    sabuj -> 0 팔리어

  • +0

    글쎄, 나는 문자열을 사용할 수 없다.h libary 함수 및 정말 포인터를 사용하는 방법을 알고 있지만 정말 고마워요! –

    +0

    @ GalElmaleh, 설명과 함께 답변을 업데이트합니다. 확인할 수 있습니다. –

    +0

    그리고 단어를 나누는 것에 관해서는 공간을 찾은 다음 for space 체크를하고 다시 반복을 시작하고 공간 처리를하기 위해 for loop check를 실행할 수 있습니다. [str = str + ''와 같은 입력 된 문자열의 마지막 문자 뒤에 공백을 추가해야합니다. –

    0

    대신 fgets를 사용 gets를 사용하지 마십시오.

    #include <stdio.h> 
    #include <stdlib.h> 
    #include <string.h> 
    
    #define STRSIZE 81 
    
    int is_palindrome(char *word); 
    
    int 
    main(void) { 
        char str[STRSIZE]; 
        size_t slen; 
        char *word; 
        const char *delim = " "; 
        int ispal = 0; 
    
        printf("Enter some text: "); 
        if (fgets(str, STRSIZE, stdin) == NULL) { 
         printf("Cannot read text into buffer.\n"); 
         exit(EXIT_FAILURE); 
        } 
    
        slen = strlen(str); 
        if (slen > 0) { 
         if (str[slen-1] == '\n') { 
          str[slen-1] = '\0'; 
         } else { 
          printf("Too many characters entered.\n"); 
          exit(EXIT_FAILURE); 
         } 
        } 
    
        if (!*str) { 
         printf("No text entered.\n"); 
         exit(EXIT_FAILURE); 
        } 
    
        word = strtok(str, delim); 
        while (word != NULL) { 
         if (is_palindrome(word)) { 
          ispal++; 
         } 
         word = strtok(NULL, delim); 
        } 
    
        printf("%d palindromic words found.\n", ispal); 
        return 0; 
    } 
    
    int 
    is_palindrome(char *word) { 
        int start, end; 
    
        if (!word) { 
         return 0; 
        } 
    
        if (strlen(word) == 1) { 
         return 1; 
        } 
    
        start = 0; 
        end = strlen(word) - 1; 
        while (start < end) { 
         if (word[start++] != word[end--]) { 
          return 0; 
         } 
        } 
    
        return 1; 
    } 
    
    0
    import java.util.Scanner; 
    
    public class Javatips { 
    
        public static void main(String[] args) { 
         Scanner in = new Scanner(System.in); 
         String x = in.next(); 
         int n = x.length(); 
         boolean isPalindrom = true; 
         for (int i = 0; i < n/2 - 1; i++) { 
          if (x.charAt(i) == x.charAt(n - 1 - i)) { 
           isPalindrom = true; 
          } else { 
           isPalindrom = false; 
          } 
          if (isPalindrom) { 
           System.out.println("the String " + x + " is palindrom"); 
          } else { 
           System.out.println("the String " + x + " is not palindrom"); 
          } 
         } 
        } 
    } 
    
    +0

    여기에 mycode가 있습니다. – Florin