Leetcode 125 Why fail - string

My code is as below:
When the input is
"A man, a plan, a canal: Panama", I got false, which is wrong. Can anyone tell me why? Thanks!
class Solution {
public boolean isPalindrome(String s) {
String fixedS = "";
for(char a: s.toCharArray()){
if(Character.isLetter(a) || Character.isDigit(a)){
fixedS += a;
}
fixedS = fixedS.toLowerCase();
int start = 0;
int end = fixedS.length()-1;
while(start <= end){
if(fixedS.charAt(start) != fixedS.charAt(end)){
return false;
}
start++;
end--;
}
}return true;
}
}

Related

I have written code to find whether given string is anagram. for some permutations code is working fine but in some case it's failing. Any suggestion?

The above logic is working for some inputs but it get's fails while we apply some complex permutations of string. Please could anyone suggest any improvement in code and logic.
public class StringAnagram {
public static void main(String[] args) {
String s = "he_llo";
String s1 = "elloh";
boolean flag = false;
if (s.length() == s1.length()) {
for (int i = 0; i < s.length(); i++) {
for (int j = 0; j < s.length(); j++) {
if (s.charAt(i) == s1.charAt(j)) {
flag = true;
i++;
if(i==s.length())
break;
} else
flag = false;
}
}
} else
System.out.println("String length not match");
if(flag==true)
System.out.println("Anagram");
else
System.out.println("Not Anagram");
}
}

ACODE - spoj: Suggest what might be wrong with my approach

I tried this question ACODE from spoj. If you could suggest me, what might be wrong with my approach!
Link to the question: http://www.spoj.com/problems/ACODE/
My approach:
typedef long long ll;
ll dp[27][3];
ll acode(char *A,int n,int k)
{
if(k==0)
{
ll x,y;
x=acode(A,n,1);
y=acode(A,n,2);
return (x+y);
}
if(n<0)
return 0;
else if(n==0)
{
if(k==1)
return 1;
else
return 0;
}
if(dp[n][k] != 0)
return dp[n][k];
int m;
if(k==1)
m=A[n]-'0';
else
m=10*(A[n-1]-'0')+(A[n]-'0');
if(m<27 && m!=0)
{
if(k==1)
dp[n][k] = acode(A,n-1,1)+acode(A,n-1,2);
else
dp[n][k] = acode(A,n-2,1)+acode(A,n-2,2);
}
return dp[n][k];
}
int main()
{
char A[5001];
cin>>A;
cout<<A;
while(strcmp(A,0))
{
int l = strlen(A);
cout<<acode(A,l-1,0)<<endl;
cin>>A;
}
return 0;
}
Using top-down DP.Memoization of each index value for k=1 or k=2.

Isomorphic Strings

Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.
For example,
Given "egg", "add", return true.
Given "foo", "bar", return false.
Given "paper", "title", return true.
Note:
You may assume both s and t have the same length.
I have this solution but it is taking too much time.
Any good solution will be appreciated
public boolean isIsomorphic(String s, String t) {
String resString1="",resString2="";
HashMap<Character,Integer> hashmapS = new HashMap();
HashMap<Character,Integer> hashmapT = new HashMap();
boolean flag = false;
for(int i = 0;i<s.length();i++)
{
char chS = s.charAt(i);
char chT = t.charAt(i);
if(hashmapS.containsKey(chS))
{
resString1 = resString1 + hashmapS.get(chS);
}
else
{
resString1 = resString1 + i;
hashmapS.put(chS, i);
}
if(hashmapT.containsKey(chT))
{
resString2 = resString2 + hashmapT.get(chT);
}
else
{
resString2 = resString2 + i;
hashmapT.put(chT, i);
}
}
if(resString1.equals(resString2))
return true;
else
return false;
}
/* Time complexity = O(n)*/
public static boolean isIsomorphic (String s1 , String s2){
if (s1 == null || s2 == null){
throw new IllegalArgumentException();
}
if (s1.length() != s2.length()){
return false;
}
HashMap<Character, Character> map = new HashMap<>();
for (int i = 0 ; i < s1.length(); i++){
if (!map.containsKey(s1.charAt(i))){
if(map.containsValue(s2.charAt(i))){
return false;
}
else{
map.put(s1.charAt(i), s2.charAt(i));
}
}
else{
if( map.get(s1.charAt(i)) != s2.charAt(i)){
return false;
}
}
}
return true;
}
In your implementation, you will come to know of the answer only after processing both strings completely. While in many negative test cases, answer can be determined seeing the first violation itself.
For e.g. consider 1000 character long strings: "aa.." and "ba....". An elegant solution would have to return seeing the second character itself of two strings, as 'a' cannot map to both 'a' and 'b' here.
You may find this article helpful. It also points to a C++ based solution.
Important thing to note are:
Since number of possible elements will be max pow(2, sizeof(char)), it is helpful to keep your own hash with ASCII code being the key itself. It gives significant improvement over the use of generic hash tables.
In Case of C++, use of std::urordered_map is better than std::map and std::stl as the later one uses Balanced Binary Search trees only.
Here is another implementation but with less memory usage.
public class IsoMorphic {
private static boolean isIsomorphic(String s, String t) {
if (s.length() != t.length()) {
return false;
}
char characters1[] = new char[26];
char characters2[] = new char[26];
char array1[] = s.toCharArray();
char array2[] = t.toCharArray();
for (int i=0; i<array1.length; i++) {
char c1 = array1[i];
char c2 = array2[i];
char character1 = characters1[c1-'a'];
char character2 = characters2[c2-'a'];
if (character1 == '\0' && character2 == '\0') {
characters1[c1-'a'] = array2[i];
characters2[c2-'a'] = array1[i];
continue;
}
if (character1 == array2[i] && character2 == array1[i]) {
continue;
}
return false;
}
return true;
}
public static void main(String[] args) {
System.out.println(isIsomorphic("foo", "bar")); // false
System.out.println(isIsomorphic("bar", "foo")); // false
System.out.println(isIsomorphic("paper", "title")); // true
System.out.println(isIsomorphic("title", "paper")); // true
System.out.println(isIsomorphic("apple", "orange")); // false
System.out.println(isIsomorphic("aa", "ab")); // false
System.out.println(isIsomorphic("ab", "aa")); // false
}
}
http://www.programcreek.com/2014/05/leetcode-isomorphic-strings-java/
You should be figuring out the algorithm by yourself though.
Two words are called isomorphic if the letters in single word can be remapped to get the second word. Remapping a letter means supplanting all events of it with another letter while the requesting of the letters stays unaltered. No two letters may guide to the same letter, yet a letter may guide to itself.
public bool isomorphic(string str1, string str2)
{
if (str1.Length != str2.Length)
{
return false;
}
var str1Dictionary = new Dictionary<char, char>();
var str2Dictionary = new Dictionary<char, char>();
var length = str1.Length;
for (int i = 0; i < length; i++)
{
if (str1Dictionary.ContainsKey(str1[i]))
{
if (str1Dictionary[str1[i]] != str2[i])
{
return false;
}
}
else
{
str1Dictionary.Add(str1[i], str2[i]);
}
if (str2Dictionary.ContainsKey(str2[i]))
{
if (str2Dictionary[str2[i]] != str1[i])
{
return false;
}
}
else
{
str2Dictionary.Add(str2[i], str1[i]);
}
}
return true;
}
public class Isomorphic {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(isIsomorphic("foo", "bar"));
System.out.println(isIsomorphic("bar", "foo"));
System.out.println(isIsomorphic("foo", "bar"));
System.out.println(isIsomorphic("bar", "foo"));
System.out.println(isIsomorphic("turtle", "tletur"));
System.out.println(isIsomorphic("tletur", "turtle"));
System.out.println(isIsomorphic("turtle", "tletur"));
System.out.println(isIsomorphic("tletur", "turtle"));
}
public static boolean isIsomorphic(String s1,String s2) {
if(s1.length()!=s2.length()) {
return false;
}
if(s1.length()==1) {
return true;
}
int c1;
int c2;
for(int i=0;i<s1.length()-1;i++) {
c1=s1.charAt(i);
c2=s1.charAt(i+1);
if(c1==c2) {
c1=s2.charAt(i);
c2=s2.charAt(i+1);
if(c1==c2) {
continue;
}else {
return false;
}
}else if(c1!=c2) {
c1=s2.charAt(i);
c2=s2.charAt(i+1);
if(c1!=c2) {
continue;
}else {
return false;
}
}
}
return true;
}
}
Comments are welcome !!
public bool IsIsomorphic(string s, string t)
{
if (s == null || s.Length <= 1) return true;
Dictionary<char, char> map = new Dictionary<char, char>();
for (int i = 0; i < s.Length; i++)
{
char a = s[i];
char b = t[i];
if (map.ContainsKey(a))
{
if (map[a]==b)
continue;
else
return false;
}
else
{
if (!map.ContainsValue(b))
map.Add(a, b);
else return false;
}
}
return true;
}
Here is my implementation...
private static boolean isIsmorphic(String string1, String string2) {
if(string1==null) return false;
if(string2==null) return false;
if(string1.length()!=string2.length())return false;
HashMap<Character,Character> map=new HashMap<>();
for(int i=0;i<string1.length();i++){
char c1=string1.charAt(i);
char c2=string2.charAt(i);
if(map.get(c1)!=null && !map.get(c1).equals(c2)){
return false;
}
map.put(c1, c2);
}
return true;
}
public class Solution {
public boolean isIsomorphic(String s, String t) {
int[] m = new int[512];
for (int i = 0; i < s.length(); i++) {
if (m[s.charAt(i)] != m[t.charAt(i)+256]) return false;
m[s.charAt(i)] = m[t.charAt(i)+256] = i+1;
}
return true;
}
}
I didn't find an answer without using Maps here, so posting my implementation which don't use additional memory.
Actually using HashMap to check if words are isomorphic is very slow on short words. On my computer using the implementation is faster up to 20 symbols in test words.
static boolean isIsomorphic(String s1, String s2) {
if (s1 == null || s2 == null) return false;
final int n = s1.length();
if (n != s2.length()) return false;
for (int i = 0; i < n; i++) {
final char c1 = s1.charAt(i);
final char c2 = s2.charAt(i);
for (int j = i + 1; j < n; j++) {
if (s1.charAt(j) == c1 && s2.charAt(j) != c2) return false;
if (s2.charAt(j) == c2 && s1.charAt(j) != c1) return false;
}
}
return true;
}
Java implementation using HashMap and HashSet. O(N) = n, O(S) = c, where c is the size of the character set.
boolean isIsomorphic(String s, String t){
HashMap<Character, Character> map = new HashMap<>();
HashSet<Character> set = new HashSet<>();
if(s.length() != t.length())
return false;
for (int i = 0; i < s.length(); i++) {
if(map.containsKey(s.charAt(i))){
if(map.get(s.charAt(i)) != t.charAt(i))
return false;
} else if(set.contains(t.charAt(i))) {
return false;
} else {
map.put(s.charAt(i), t.charAt(i));
set.add(t.charAt(i));
}
}
return true;
}
There are many different ways on how to do it. Below I provided three different ways by using a dictionary, set, and string.translate.
Here I provided three different ways how to solve Isomorphic String solution in Python.
This is the best solution I think
public boolean areIsomorphic(String s1,String s2)
{
if(s1.length()!=s2.length())
return false;
int count1[] = new int[256];
int count2[] = new int[256];
for(int i=0;i<s1.length();i++)
{
if(count1[s1.charAt(i)]!=count2[s2.charAt(i)])
return false;
else
{
count1[s1.charAt(i)]++;
count2[s2.charAt(i)]++;
}
}
return true;
}
C# soluation:
public bool isIsomorphic(String string1, String string2)
{
if (string1 == null || string2 == null)
return false;
if (string1.Length != string2.Length)
return false;
var data = new Dictionary<char, char>();
for (int i = 0; i < string1.Length; i++)
{
if (!data.ContainsKey(string1[i]))
{
if (data.ContainsValue(string2[i]))
return false;
else
data.Add(string1[i], string2[i]);
}
else
{
if (data[string1[i]] != string2[i])
return false;
}
}
return true;
}

How can I correct the error "Cross-thread operation not valid"?

This following code gives me the error below . I think I need "InvokeRequired" . But I don't understand how can I use?
error:Cross-thread operation not valid: Control 'statusBar1' accessed from a thread other than the thread it was created on.
the code :
public void CalculateGeneration(int nPopulation, int nGeneration)
{
int _previousFitness = 0;
Population TestPopulation = new Population();
for (int i = 0; i < nGeneration; i++)
{
if (_threadFlag)
break;
TestPopulation.NextGeneration();
Genome g = TestPopulation.GetHighestScoreGenome();
if (i % 100 == 0)
{
Console.WriteLine("Generation #{0}", i);
if ( ToPercent(g.CurrentFitness) != _previousFitness)
{
Console.WriteLine(g.ToString());
_gene = g;
statusBar1.Text = String.Format("Current Fitness = {0}", g.CurrentFitness.ToString("0.00"));
this.Text = String.Format("Sudoko Grid - Generation {0}", i);
Invalidate();
_previousFitness = ToPercent(g.CurrentFitness);
}
if (g.CurrentFitness > .9999)
{
Console.WriteLine("Final Solution at Generation {0}", i);
statusBar1.Text = "Finished";
Console.WriteLine(g.ToString());
break;
}
}
}
}
Easiest for reusability is to add a helper function like:
void setstatus(string txt)
{
Action set = () => statusBar1.Text = txt;
statusBar1.Invoke(set);
}
Or with the invokerequired check first:
delegate void settextdelegate(string txt);
void setstatus(string txt)
{
if (statusBar1.InvokeRequired)
statusBar1.Invoke(new settextdelegate(setstatus), txt);
else
statusBar1.Text = txt;
}
Either way the status can then be set like
setstatus("Finished");
For completeness I should add that even better would be to keep your calculating logic separated from your form and raise a status from within your calculating functionality that can be hanled by the form, but that could be completely out of scope here.

Substring algorithm

Can someone explain to me how to solve the substring problem iteratively?
The problem: given two strings S=S1S2S3…Sn and T=T1T2T3…Tm, with m is less than or equal to n, determine if T is a substring of S.
Here's a list of string searching algorithms
Depending on your needs, a different algorithm may be a better fit, but Boyer-Moore is a popular choice.
A naive algorithm would be to test at each position 0 < i ≤ n-m of S if Si+1Si+2…Si+m=T1T2…Tm. For n=7 and m=5:
i=0: S1S2S3S4S5S6S7
| | | | |
T1T2T3T4T5
i=1: S1S2S3S4S5S6S7
| | | | |
T1T2T3T4T5
i=2: S1S2S3S4S5S6S7
| | | | |
T1T2T3T4T5
The algorithm in pseudo-code:
// we just need to test if n ≤ m
IF n > m:
// for each offset on that T can start to be substring of S
FOR i FROM 0 TO n-m:
// compare every character of T with the corresponding character in S plus the offset
FOR j FROM 1 TO m:
// if characters are equal
IF S[i+j] == T[j]:
// if we’re at the end of T, T is a substring of S
IF j == m:
RETURN true;
ENDIF;
ELSE:
BREAK;
ENDIF;
ENDFOR;
ENDFOR;
ENDIF;
RETURN false;
Not sure what language you're working in, but here's an example in C#. It's a roughly n2 algorithm, but it will get the job done.
bool IsSubstring (string s, string t)
{
for (int i = 0; i <= (s.Length - t.Length); i++)
{
bool found = true;
for (int j = 0; found && j < t.Length; j++)
{
if (s[i + j] != t[j])
found = false;
}
if (found)
return true;
}
return false;
}
if (T == string.Empty) return true;
for (int i = 0; i <= S.Length - T.Length; i++) {
for (int j = 0; j < T.Length; j++) {
if (S[i + j] == T[j]) {
if (j == (T.Length - 1)) return true;
}
else break;
}
}
return false;
It would go something like this:
m==0? return true
cs=0
ct=0
loop
cs>n-m? break
char at cs+ct in S==char at ct in T?
yes:
ct=ct+1
ct==m? return true
no:
ct=0
cs=cs+1
end loop
return false
This may be redundant with the above list of substring algorithms, but I was always amused by KMP (http://en.wikipedia.org/wiki/Knuth–Morris–Pratt_algorithm)
// runs in best case O(n) where no match, worst case O(n2) where strings match
var s = "hippopotumus"
var t = "tum"
for(var i=0;i<s.length;i++)
if(s[i]==t[0])
for(var ii=i,iii=0; iii<t.length && i<s.length; ii++, iii++){
if(s[ii]!=t[iii]) break
else if (iii==t.length-1) console.log("yay found it at index: "+i)
}
Here is my PHP variation that includes a check to make sure the Needle does not exceed the Haystacks length during the search.
<?php
function substring($haystack,$needle) {
if("" == $needle) { return true; }
echo "Haystack:\n$haystack\n";
echo "Needle:\n$needle\n";
for($i=0,$len=strlen($haystack);$i<$len;$i++){
if($needle[0] == $haystack[$i]) {
$found = true;
for($j=0,$slen=strlen($needle);$j<$slen;$j++) {
if($j >= $len) { return false; }
if($needle[$j] != $haystack[$i+$j]) {
$found = false;
continue;
}
}
if($found) {
echo " . . . . . . SUCCESS!!!! startPos: $i\n";
return true;
}
}
}
echo " . . . . . . FAILURE!\n" ;
return false;
}
assert(substring("haystack","hay"));
assert(!substring("ack","hoy"));
assert(substring("hayhayhay","hayhay"));
assert(substring("mucho22","22"));
assert(!substring("str","string"));
?>
Left in some echo's. Remove if they offend you!
Is a O(n*m) algorithm, where n and m are the size of each string.
In C# it would be something similar to:
public static bool IsSubtring(char[] strBigger, char[] strSmall)
{
int startBigger = 0;
while (startBigger <= strBigger.Length - strSmall.Length)
{
int i = startBigger, j = 0;
while (j < strSmall.Length && strSmall[j] == strBigger[i])
{
i++;
j++;
}
if (j == strSmall.Length)
return true;
startBigger++;
}
return false;
}
I know I'm late to the game but here is my version of it (in C#):
bool isSubString(string subString, string supraString)
{
for (int x = 0; x <= supraString.Length; x++)
{
int counter = 0;
if (subString[0] == supraString[x]) //find initial match
{
for (int y = 0; y <= subString.Length; y++)
{
if (subString[y] == supraString[y+x])
{
counter++;
if (counter == subString.Length)
{
return true;
}
}
}
}
}
return false;
}
Though its pretty old post, I am trying to answer it. Kindly correct me if anything is wrong,
package com.amaze.substring;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CheckSubstring {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter the main string");
String mainStr = br.readLine();
System.out.println("Enter the substring that has to be searched");
String subStr = br.readLine();
char[] mainArr = new char[mainStr.length()];
mainArr = mainStr.toCharArray();
char[] subArr = new char[subStr.length()];
subArr = subStr.toCharArray();
boolean tracing = false;
//System.out.println("Length of substring is "+subArr.length);
int j = 0;
for(int i=0; i<mainStr.length();i++){
if(!tracing){
if(mainArr[i] == subArr[j]){
tracing = true;
j++;
}
} else {
if (mainArr[i] == subArr[j]){
//System.out.println(mainArr[i]);
//System.out.println(subArr[j]);
j++;
System.out.println("Value of j is "+j);
if((j == subArr.length)){
System.out.println("SubString found");
return;
}
} else {
j=0;
tracing = false;
}
}
}
System.out.println("Substring not found");
}
}

Resources