timeNomad - 6 months ago 97

Java Question

So I've been trying to solve this assignment whole day, just can't get it.

The following function accepts 2 strings, the 2nd (not 1st) possibly containing

`*`

An

`*`

`*`

`ab**c`

`public static boolean samePattern(String s1, String s2)`

It returns true if strings are of the same pattern.

It must be

Can use local variables & method overloading.

Can use only these methods: charAt(i), substring(i), substring(i, j), length().

Examples:

1:

`TheExamIsEasy`

`The*xamIs*y`

1:

`TheExamIsEasy`

`Th*mIsEasy*`

1:

`TheExamIsEasy`

`*`

1:

`TheExamIsEasy`

`TheExamIsEasy`

1:

`TheExamIsEasy`

`The*IsHard`

I tried comparing the the chars one by one using charAt until an asterisk is encountered, then check if the asterisk is an empty one by comparing is successive char (i+1) with the char of s1 at position i, if true -- continue recursion with i+1 as counter for s2 & i as counter for s1; if false -- continue recursion with i+1 as counters for both.

Continue this until another asterisk is found or end of string.

I dunno, my brain loses track of things, can't concentrate, any

Also, it's been told that a

My code so far (doesn't do the job, even theoretically):

`public static boolean samePattern(String s1, String s2) {`

if (s1.equals(s2) || s2 == "*") {

return true;

}

return samePattern(s1, s2, 1);

}

public static boolean samePattern(String s1, String s2, int i)

{

if (s1.equals(s2))

return true;

if (i == s2.length() - 1) // No *'s found -- not same pattern.

return false;

if (s1.substring(0, i).equals(s2.substring(0, i)))

samePattern(s1, s2, i+1);

else if (s2.charAt(i-1) == '*')

samePattern(s1.substring(0, i-1), s2.substring(0, i), 1); // new smaller strings.

else

samePattern(s1.substring(1), s2, i);

}

Answer

Here's some Python "psudocode" that may help

```
def samePattern(s1,s2):
if s2=="*" or s1==s2: return True
if s1=="": return False
if s1[0]==s2[0]: return samePattern(s1[1:],s2[1:])
if s2[0]=="*": return samePattern(s1,s2[1:]) or samePattern(s1[1:],s2)
return False
```

Here is a rough guide for converting the code

```
s[0] = the first character
s[1:] = the string minus the first character
```