mirror of
https://github.com/arkorty/LeetCode.git
synced 2026-03-18 00:57:17 +00:00
Initial commit
This commit is contained in:
28
Medium/longest-palindromic-substring/Solution.java
Normal file
28
Medium/longest-palindromic-substring/Solution.java
Normal file
@@ -0,0 +1,28 @@
|
||||
class Solution {
|
||||
public String longestPalindrome(String line) {
|
||||
if (line.length() < 2) {
|
||||
return line;
|
||||
} else {
|
||||
int start = 0, size = 0, left = 0, right = 0, middle = 0;
|
||||
while (middle < line.length()) {
|
||||
left = right = middle;
|
||||
while (right < line.length() - 1 && line.charAt(right) == line.charAt(right + 1)) {
|
||||
++right;
|
||||
}
|
||||
|
||||
middle = right + 1;
|
||||
while (left > 0 && right < line.length() - 1 && line.charAt(left - 1) == line.charAt(right + 1)) {
|
||||
--left;
|
||||
++right;
|
||||
}
|
||||
|
||||
if (right - left + 1 > size) {
|
||||
start = left;
|
||||
size = right - left + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return line.substring(start, start + size);
|
||||
}
|
||||
}
|
||||
}
|
||||
33
Medium/longest-palindromic-substring/solution.cpp
Normal file
33
Medium/longest-palindromic-substring/solution.cpp
Normal file
@@ -0,0 +1,33 @@
|
||||
#include <string>
|
||||
|
||||
class Solution {
|
||||
public:
|
||||
std::string longestPalindrome(std::string line) {
|
||||
if (line.size() < 2) {
|
||||
return line;
|
||||
} else {
|
||||
int size = 0, start = 0, left = 0, right = 0, middle = 0;
|
||||
while (middle < line.size()) {
|
||||
left = middle, right = middle;
|
||||
while (right < line.size() - 1 &&
|
||||
line[right] == line[right + 1]) {
|
||||
++right;
|
||||
}
|
||||
|
||||
middle = right + 1;
|
||||
while (right < line.size() - 1 && left > 0 &&
|
||||
line[right + 1] == line[left - 1]) {
|
||||
--left;
|
||||
++right;
|
||||
}
|
||||
|
||||
if (right - left + 1 > size) {
|
||||
start = left;
|
||||
size = right - left + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return line.substr(start, size);
|
||||
}
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user