Here is the problem link: https://leetcode.com/problems/roman-to-integer/
I kept having problem on comparison s.charAt() and a char of Roman.
I am very new to JAVA. Isn't if(s.charAt(i) == 'I') supposed to work?
I saw other solutions of this problem, but the solutions tend to make a char and put the char of string in that char.
Could you please explain why my comparison is not working?
I really appreciate your answer in advance.
class Solution {
public int romanToInt(String s) {
int i = 0;
int sum = 0;
for(i=0;i<s.length();i++)
{
if(s.charAt(i) == 'I')
{
if(s.charAt(i+1) == 'X') //4
{
i++;
sum += 4;
}
else if(s.charAt(i+1) == 'V') //9
{
i++;
sum += 9;
}
else
{
sum += 1;
}
}
else if(s.charAt(i) == 'V')
{
sum += 10;
}
else if(s.charAt(i) == 'X')
{
if(s.charAt(i+1) == 'L') //40
{
i++;
sum += 40;
}
else if(s.charAt(i+1) == 'C') //90
{
i++;
sum += 90;
}
else
{
sum += 10;
}
}
else if(s.charAt(i) == 'L')
{
sum += 50;
}
else if(s.charAt(i) == 'C')
{
if(s.charAt(i+1) == 'D') //400
{
i++;
sum += 400;
}
else if(s.charAt(i+1) == 'M') //900
{
i++;
sum += 900;
}
else
{
sum+=100;
}
}
else if(s.charAt(i) == 'D')
{
sum += 500;
}
else if(s.charAt(i) == 'M')
{
sum += 1000;
}
}
return sum;
}
}
I used Java for this:
public int romanToInt(String s) {
HashMap<Character, Integer> dict = new HashMap<Character, Integer>();
{
dict.put('I', 1);
dict.put('V', 5);
dict.put('X', 10);
dict.put('L', 50);
dict.put('C', 100);
dict.put('D', 500);
dict.put('M', 1000);
}
int temp = 0;
for(int i=0; i<s.length(); i++){
char c= s.charAt(i);
temp += dict.get(c);
char d= '.';
if((i+1)<s.length() && d!=c){
d = s.charAt(i+1);
if((c=='I' && (d=='V' || d=='X')) ||
(c=='X' && (d=='L' || d=='C')) ||
(c=='C' && (d=='D' || d=='M')))
{
temp += dict.get(d)-2*dict.get(c);
i++;
}
}
}
return temp;
}
Related
Hi I was trying to solve the interleaving strings problem.Here is the detailed explanation of the problem. https://practice.geeksforgeeks.org/problems/interleaved-strings/1
I was trying using lcs but it was not passing leetcode cases. Here is my Code:-
(I am taking lcs from start and end)
class Solution {
public boolean isInterLeave(String a, String b, String c) {
StringBuffer s=new StringBuffer();
StringBuffer s1=new StringBuffer();
StringBuffer s2=new StringBuffer();
StringBuffer s4=new StringBuffer();
int m=a.length();
int n=c.length();
int q=b.length();
if(n!=m+q){
return false;
}
LinkedHashSet<Integer> res2= new LinkedHashSet<Integer>();
res2= lcs(a,c,m,n);
LinkedHashSet<Integer> res4= new LinkedHashSet<Integer>();
res4= lcs(b,c,q,n);
for(int i=0;i<n;i++){
if(res2.contains(i)==false){
s.append(c.charAt(i));
}
}
for(int i=0;i<n;i++){
if(res4.contains(i)==false){
s1.append(c.charAt(i));
}
}
LinkedHashSet<Integer> res5= new LinkedHashSet<Integer>();
res5= LCS(a,c,m,n);
for(int i=0;i<n;i++){
if(res5.contains(i)==false){
s2.append(c.charAt(i));
}
} LinkedHashSet<Integer> res6= new LinkedHashSet<Integer>();
res6= LCS(b,c,q,n);
for(int i=0;i<n;i++){
if(res6.contains(i)==false){
s4.append(c.charAt(i));
}
}
String z=s.toString();
String u=s1.toString();
String v=s2.toString();
String w=s4.toString();
if( (b.equals(z)==true || a.equals(u)==true) || ( b.equals(v)==true || a.equals(w)==true)){
return true;
}
else{
return false;
}
}
public static LinkedHashSet<Integer> lcs(String X, String Y, int m, int n)
{
int[][] L = new int[m+1][n+1];
// Following steps build L[m+1][n+1] in bottom up fashion. Note
// that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1]
for (int i=0; i<=m; i++)
{
for (int j=0; j<=n; j++)
{
if (i == 0 || j == 0)
L[i][j] = 0;
else if (X.charAt(i-1) == Y.charAt(j-1))
L[i][j] = L[i-1][j-1] + 1;
else
L[i][j] = Math.max(L[i-1][j], L[i][j-1]);
}
}
// Following code is used to print LCS
// Create a character array to store the lcs string
LinkedHashSet<Integer> linkedset =
new LinkedHashSet<Integer>();
// Start from the right-most-bottom-most corner and
// one by one store characters in lcs[]
int i=1;
int j=1;
while (i <= m && j <= n)
{
// If current character in X[] and Y are same, then
// current character is part of LCS
if (X.charAt(i-1) == Y.charAt(j-1))
{
// Put current character in result
linkedset.add(j-1);
// reduce values of i, j and index
i++;
j++;
}
// If not same, then find the larger of two and
// go in the direction of larger value
else if (L[i-1][j] > L[i][j-1])
i++;
else
j++;
}
return linkedset;
}
public static LinkedHashSet<Integer> LCS(String X, String Y, int m, int n)
{
int[][] L = new int[m+1][n+1];
// Following steps build L[m+1][n+1] in bottom up fashion. Note
// that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1]
for (int i=0; i<=m; i++)
{
for (int j=0; j<=n; j++)
{
if (i == 0 || j == 0)
L[i][j] = 0;
else if (X.charAt(i-1) == Y.charAt(j-1))
L[i][j] = L[i-1][j-1] + 1;
else
L[i][j] = Math.max(L[i-1][j], L[i][j-1]);
}
}
// Following code is used to print LCS
// Create a character array to store the lcs string
LinkedHashSet<Integer> linkedset =
new LinkedHashSet<Integer>();
// Start from the right-most-bottom-most corner and
// one by one store characters in lcs[]
int i = m;
int j = n;
while (i > 0 && j > 0)
{
// If current character in X[] and Y are same, then
// current character is part of LCS
if (X.charAt(i-1) == Y.charAt(j-1))
{
// Put current character in result
linkedset.add(j-1);
// reduce values of i, j and index
i--;
j--;
}
// If not same, then find the larger of two and
// go in the direction of larger value
else if (L[i-1][j] > L[i][j-1])
i--;
else
j--;
}
return linkedset;
}
}
Can anyone suggest an LCS approach to this problem?.My code is not passing the following test case
"cacabcbaccbbcbb" -String A
"acaaccaacbbbabbacc"-String B
"accacaabcbacaccacacbbbbcbabbbbacc"-String C
This will be the LCS+DP approach. Try it out:
class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
int m = s1.length(), n = s2.length();
if (n + m != s3.length()) return false;
if (s3.length() == 0) return true;
boolean[][] dp = new boolean[m+1][n+1];
dp[0][0] = true;
for (int i = 0; i <= m; i++) {
if (s1.substring(0, i).equals(s3.substring(0, i)))
dp[i][0] = true;
else
dp[i][0] = false;
}
for (int j = 0; j <= n; j++) {
if (s2.substring(0, j).equals(s3.substring(0, j)))
dp[0][j] = true;
else
dp[0][j] = false;
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
dp[i][j] = (dp[i-1][j] && s1.charAt(i-1) == s3.charAt(i+j-1))
|| (dp[i][j-1] && s2.charAt(j-1) == s3.charAt(i+j-1));
}
}
return dp[m][n];
}
}
I'm trying to compile this program in c (for a cs50 online class), and keep getting the following error:
fifteen.c:233:1: error: control may reach end of non-void function [-Werror,-Wreturn-type]
}
I'm not asking about the logic of my code, but more looking for the syntax error that I've been missing for the last hour. Code is below. Thanks!
bool move(int tile)
{
for (int i = 0; i < d - 1; i++){
for (int j= 0; j < d - 1; j++){
if (tile == board[i][j]){
if (board[i+1][j] == tile){
board[i+1][j] = 0;
board[i+1][j] = tile;
return true;
}
else if (board [i-1][j] == 0){
board[i-1][j] = tile;
board [i-1][j] = 0;
return true;
}
else if (board [i][j+1] == 0){
board[i][j+1] = tile;
board [i][j+1] = 0;
return true;
}
else if (board [i][j-1] == 0){
board[i][j-1] = tile;
board [i][j-1] = 0;
return true;
}
}
return false;
}
}
}
This error is saying that your method can reach the end without returning a value. This is happening in this case because your brackets are out of place.
Try the following:
bool move(int tile) {
for (int i = 0; i < d - 1; i++) {
for (int j = 0; j < d - 1; j++) {
if (tile == board[i][j]) {
if (board[i+1][j] == tile) {
board[i+1][j] = 0;
board[i+1][j] = tile;
return true;
}
else if (board [i-1][j] == 0){
board[i-1][j] = tile;
board [i-1][j] = 0;
return true;
}
else if (board [i][j+1] == 0){
board[i][j+1] = tile;
board [i][j+1] = 0;
return true;
}
}
else if (board [i][j-1] == 0){
board[i][j-1] = tile;
board [i][j-1] = 0;
return true;
}
}
}
return false;
}
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.
I want to make this game in Processing.
When in 'Switch' those are displayed case0,1,2 in same time.
I don't know how to edit it.
and after case2(gameover), press key '1' to start again.
but I think it goes to case1 when gameover situation...
How can I edit it??
PImage work[] = new PImage[3];
float workSize[] = new float[3];
float workX[] = new float[3];
float workY[] = new float[3];
float workS[] = new float[3];
PImage handA, handB;
PFont font;
int level;
boolean gameover = false;
boolean selected[] = new boolean [3];
int salary = 0;
void setup(){
size(1000,800);
background(255);
imageMode(CENTER);
for (int i=0; i<3; i++) {
workX[i] = random(0, width);
workY[i] = random(0, height);
selected[i] = false;
workSize[i] = 120;
}
handA = loadImage("handA.png");
handB = loadImage("handB.png");
work[0] = loadImage("work0.png");
work[1] = loadImage("work1.png");
work[2] = loadImage("work2.png");
font = createFont("Gulim", 48);
textFont(font);
textAlign(CENTER, CENTER);
}
void draw(){
background(255);
if (mousePressed) {
cursor(handB, 0, 0);
} else {
cursor(handA, 0, 0);
}
switch (level) {
default: // press'1' to start game
fill(0);
text("1을 눌러 일 얻기", width/2, height/2);
if (key == '1') {
level = 1;
}
break;
case 1:
game();
if (gameover == true) {
level = 2;
}
break;
case 2: // press '1' to start again
fill(0);
text("퇴직금 : "+ salary + " + (비정규직으로 퇴직금 없음)", width/2, height/2-100);
text("일을 못해서 정리해고", width/2, height/2);
text("1을 눌러 다시 일 얻기", width/2, height/2+100);
if (key == '1') {
level = 1;
}
break;
}
}
void game() {
for (int i=0; i<3; i++) {
float clickedDist = dist(workX[i], workY[i], mouseX, mouseY);
if (clickedDist<workSize[i]/2 && mousePressed) {
workSize[i] = workSize[i] - 2;
} else {
workSize[i] = workSize[i] + 0.7;
}
if (workSize[i]<100) {
workSize[i] = 0;
}
if (workSize[i]>400) {
gameover = true;
}
if (workSize[i] == 0 && selected[i] == false) {
salary = salary + 50;
selected[i] = true;
workX[i] = random(0, width);
workY[i] = random(0, height);
selected[i] = false;
workSize[i] = 120;
}
if (salary > 150) {
workS[i] = workSize[i] + 0.5;
workSize[i] = workS[i];
}
if (abs(mouseX-workX[i]) < workSize[i]/2 && abs(mouseY-workY[i]) < workSize[i]/2) {
workX[i] += random(-5,5);
workY[i] += random(-5,5);
}
image(work[i], workX[i], workY[i], workSize[i], workSize[i]);
pushMatrix();
fill(0);
textSize(48);
text("봉급 : "+ salary, textWidth("salary"), (textAscent()+textDescent()/2));
popMatrix();
}
}
All you have to do is reset any variables that store the state of your game, such as your level variable. Something like this:
void keyPressed(){
if(gameover && key == '1'){
gameover = false;
level = 1;
}
}
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");
}
}