51 Adjacent pair not Equal

51

Problem of the Day:
Problem Statement You are given two strings s1 and s2 of equal length.
Consider every adjacent pair of characters (substring of length 2) from both strings.
Your task is to return all adjacent pairs where the pair in s1 is not equal to the pair in s2.
Each result should be represented as "pair1-pair2"..
  • 1.Input
    s1 = "abcdef"
    s2 = "abcfed"
    Output:
    ["d-f", "d-f", "f-d"];

  • 2.Input: s1 = "asdfghij"
    s2 = "adsfgijh"
    Output:
    ["sd-ds", "hij-ijh"]
.snippet-thumbnail img { max-width: 50px; height: auto; object-fit: cover; }

Comments

  1. public class AdjacentPairsNotEqual {
    public static void main(String[] args) {
    String s1 = "asdfghij";
    String s2 = "adsfgijh";

    if (s1.length() != s2.length()) {
    System.out.println("Strings must be of equal length.");
    return;
    }

    int n = s1.length();
    boolean first = true;

    for (int i = 0; i < n;) {
    if (s1.charAt(i) == s2.charAt(i)) {
    i++;
    continue;
    }


    int j = i;
    String pair1 = "";
    String pair2 = "";

    while (j < n && s1.charAt(j) != s2.charAt(j)) {
    pair1 += s1.charAt(j);
    pair2 += s2.charAt(j);
    j++;
    }

    if (!first) {
    System.out.print(", ");
    }
    System.out.print(pair1 + "-" + pair2);
    first = false;

    i = j;
    }
    }
    }

    ReplyDelete

Post a Comment

Popular posts from this blog

Strings

Arrays