2016-07-13 2 views
1

C#에서 루프 함수를 사용하지 않고 문자열 함수를 사용하지 않고 문자열이 palindrome인지 여부를 확인하십시오. 문자열 함수없이 할 수 있지만 루프 문없이 확인하는 방법을 모르겠습니다. 인터뷰 중 하나에서이 질문에 직면합니다.C#에서 루프 문을 사용하지 않고 문자열 함수를 사용하지 않고 문자열이 palindrome인지 여부를 확인하십시오.

using System; 
namespace palindrome 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string s,revs=""; 
      Console.WriteLine(" Enter string"); 
      s = Console.ReadLine(); 
      for (int i = s.Length-1; i >=0; i--) //**i want to replace this for loop** 
      { 
       revs += s[i].ToString(); 
      } 
      if (revs == s) // Checking whether string is palindrome or not 
      { 
       Console.WriteLine("String is Palindrome \n Entered String Was {0} and reverse string is {1}", s, revs); 
      } 
      else 
      { 
       Console.WriteLine("String is not Palindrome \n Entered String Was {0} and reverse string is {1}", s, revs); 
      } 
      Console.ReadKey(); 
     } 
    } 
} 
+1

"문자열 함수를 사용하지 않고"무엇을 ​​의미하는지 명확하지 않지만'.Length'와'[] '를 사용할 수 있다면 재귀를 사용하여이를 수행 할 수 있습니다. –

+0

[C++ 버전] (http://stackoverflow.com/questions/34257983/how-to-check-if-string-is-palindrome-without-using-string-functions-in-c) – stuartd

+0

주어진 답은? – fubo

답변

2

내 코드가 업데이트되었습니다. 루프가없고 문자열 방법이 없습니다. 대/소문자 구분은 무시됩니다.

(안나 = 사실, 안나 = false)를

코드 :

string s = Console.ReadLine(); 
bool isPalindrome = s.SequenceEqual(s.Reverse()); 
+0

나는 string inbuilt 함수없이 원한다. –

+1

@valluriratnlababu 아니요,'Reverse'는'System.Linq.Enumerable'에서 유래되었으며 문자열 inbuilt 함수가 아닙니다. https://msdn.microsoft.com/en-us/library/bb358497(v=vs.100). aspx – fubo

4

다짜고짜 당신이 문자열을 통해 루프에있는 ; 하지만 루프를 숨기고 암시 적으로으로 만들 수 있습니다. 모두

bool result = Enumerable 
    .Range(0, s.Length) 
    .All(i => s[i] == s[s.Length - 1 - i]); 

물론이 솔루션 및 에 가까운

+0

이름은 대문자로 시작하고 작은 것으로 끝나는 회문 일 수 있기 때문에's [i] == s [s.Length - 1 -i]'와 비교할 수 없습니다. 예 :_Anna_는 회문이지만 결과는 false가됩니다. – fubo

+0

@fubo : 대소 문자를 구별하지 않으려면 * 문장을 검색해야합니다. .All (i => char.ToUpper (s [i]) == char.ToUpper * "우리는 CHAR이 아닌 STRING 메서드를 사용할 수 없습니다";) –

+0

@fubo 우리는 다음과 같은 목적으로 대소 문자를 무시해야한다고 생각합니다. 질문에 대답한다. 그것은 IMHO 문제의 핵심에서 산만입니다. –

4

부정 행위는 재귀를 사용할 수 있습니까? 때문에 그렇다면 :이 루프

class Program 
{ 
    static void Main() 
    { 
     Console.WriteLine(IsPalindrome("ABCDEFG")); // Prints false 
     Console.WriteLine(IsPalindrome("ABCDCBA")); // Prints true 
    } 

    public static bool IsPalindrome(string text) 
    { 
     return isPalindrome(0, text.Length - 1, text); 
    } 

    private static bool isPalindrome(int indexOfFirst, int indexOfLast, string text) 
    { 
     if (indexOfFirst >= indexOfLast) 
      return true; 

     if (text[indexOfFirst] != text[indexOfLast]) 
      return false; 

     return isPalindrome(indexOfFirst + 1, indexOfLast - 1, text); 
    } 
} 

없음 - 호출되는 방법에 숨겨진 심지어 어떤 비열한 작은 것들.

참고 : string.Length이고 문자열 배열 연산자는 질문의 목적으로 "문자열 함수"로 간주되지 않습니다.

0

우리 모두가 루프와 실제 문자열 기능을 직접 사용하지 않았기 때문에 모두가 기술적으로 정확하다고 말할 수 있습니까?

그러나 모든 Enumerable 확장 메서드는 확실히 어떤 시점에서 루프를 사용합니다. 배열을 순회 할 때 루프를 사용하는 것을 피할 방법이 없습니다. 미리 알고있는 경우가 아니면 배열의 요소 수를 명시 적으로 지정하지 않고 코드의 해당 배열에있는 각 요소를 명시 적으로 지정합니다 (많은 코드가됩니다).

회귀 분석을 제외하고 1,000,000 반복에 대한 타이머로 꾸며져 있습니다. 타이밍을 아주 재미있게 찾을 수 있습니다. 콘솔 앱을 사용했습니다.

 var lWatch = new Stopwatch(); 

     var s = "ABCDCBA"; 

     bool result; 
     bool isPalindrome; 

     ////Simple array element comparison 
     lWatch.Restart(); 

     for (int j = 0; j < 1000000; j++) 
      result = Enumerable 
       .Range(0, s.Length) 
       .All(i => s[i] == s[s.Length - 1 - i]); 

     lWatch.Stop(); 

     Console.WriteLine(lWatch.Elapsed); 


     ////Sequence reversal and comparison 
     lWatch.Restart(); 

     for (int j = 0; j < 1000000; j++) 
      isPalindrome = s.SequenceEqual(s.Reverse()); 

     lWatch.Stop(); 

     Console.WriteLine(lWatch.Elapsed); 


     ////Simple array element comparison; respecting casing 
     lWatch.Restart(); 

     for (int j = 0; j < 1000000; j++) 
      result = Enumerable 
       .Range(0, s.Length) 
       .All(i => char.ToUpper(s[i]) == char.ToUpper(s[s.Length - 1 - i])); 

     lWatch.Stop(); 

     Console.WriteLine(lWatch.Elapsed); 


     ////Sequence reversal and comparison; respecting casing 
     lWatch.Restart(); 

     for (int j = 0; j < 1000000; j++) 
      isPalindrome = s.Select(c => char.ToUpper(c)).SequenceEqual(s.Select(c => char.ToUpper(c)).Reverse()); 

     lWatch.Stop(); 

     Console.WriteLine(lWatch.Elapsed); 

char.ToUpper()에 대한 인수를 기억하십시오.

관련 문제