2019년 4월 13일 토요일

# 팰린드롬 Palindrome

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// 주어진 문자열이 팰린드롬이라면 길이를 리턴.
// 아니라면 -1을 리턴.
int CheckPalindrome(string s) {
 int start = 0, end = s.length() - 1;
 while (start != end) {
  if (s[start] != s[end]) {
   return -1;
  }
  else {
   start++;
   end--;
  }
 }
 return s.length();
}

// 주어진 문자열의 특정 문자를 기준으로 팰린드롬을 판단.
// 아니라면 -1, 팰린드롬이면 그 길이를 리턴.
int CheckPalindrome(string&s, int basePos) {
 int lenCount = 0;
 int left  = basePos - 1, right = basePos + 1;
 while (true) {
  if (left < 0 || right > s.length()) break;
  if (s[left] != s[right]) break;

  lenCount += 2;
  left--;
  right++;
 }
 // 기준 문자도 카운팅하여 추가.
 lenCount++;
 return lenCount;
}

댓글 없음:

댓글 쓰기