-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfirst_palindrome.cpp
More file actions
60 lines (54 loc) · 1.41 KB
/
first_palindrome.cpp
File metadata and controls
60 lines (54 loc) · 1.41 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
* =====================================================================================
*
* Filename: first_palindrome.cpp
*
* Description: 2108. Find First Palindromic String in the Array.
*
* Version: 1.0
* Created: 02/13/2024 16:27:46
* Revision: none
* Compiler: gcc
*
* Author: xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <string>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using std::string;
using std::vector;
// Two pointers
class Solution {
public:
string firstPalindrome(vector<string>& words) {
for (const string& s : words) {
if (isPalindrome(s)) {
return s;
}
}
return "";
}
bool isPalindrome(const string& s) {
for (int i = 0, j = s.size() - 1; i < j; i++, j--) {
if (s[i] != s[j]) {
return false;
}
}
return (s.size() > 0);
}
};
TEST(Solution, firstPalindrome) {
vector<std::pair<vector<string>, string>> cases = {
std::make_pair(vector<string>{"abc", "car", "ada", "racecar", "cool"}, "ada"),
std::make_pair(vector<string>{"notapalindrome", "racecar"}, "racecar"),
std::make_pair(vector<string>{"def", "ghi"}, ""),
};
for (auto& c : cases) {
EXPECT_EQ(Solution().firstPalindrome(c.first), c.second);
}
}