aramkirakosyan89
BAN USERpublic class Palindrome {
public static int findLargest(int[] numbers)
{
int largest = numbers[0];
for(int i = 1; i < numbers.length; i++){
if(numbers[i] > largest){
largest = numbers[i];
}
}
return largest;
}
public static int findLargestIndex(int[] numbers)
{
int largest = numbers[0];
int index = 0;
int i;
for(i = 1; i < numbers.length; i++){
if(numbers[i] > largest){
largest = numbers[i];
index = i;
}
}
return index;
}
public static String getLongestPalindrome(String str)
{
StringBuffer tmp = new StringBuffer(str);
StringBuffer reversedStr = tmp.reverse();
char[] buffer = new char[str.length()];
reversedStr.getChars(0, str.length(), buffer, 0);
int [] sizes = new int[str.length()];
for (int i = 0; i < str.length() - 2; i++)
{
int start = i;
int end = i + 2;
int count = 0;
CharSequence s = reversedStr.subSequence(start, end);
while (str.contains(s))
{
count ++;
s = reversedStr.subSequence(start, end + count);
}
sizes [i] = count;
}
int largest = findLargest(sizes);
int index = findLargestIndex(sizes);
return reversedStr.substring(index, index + largest +1);
}
public static void main (String[] args)
{
String substr = getLongestPalindrome("I like racecars that go fast");
System.out.println(substr);
}
}
There are many reasons why strings are immutable in Java.
- aramkirakosyan89 November 11, 2013One of the primary reasons is security. Strings used as parameter in many methods, for example for opening database connection, files, network connections. It can be easily attacked if it is mutable.
Another reason is that immutability makes String thread safe.
To calculate hashcode only once and cash it, which makes better performance for hashMaps, when Strings are used as a key.
4 objects will be created, three for storing "A", "B" , "C" and one for "ABC" (temp)