जावा प्रोग्राम यह जांचने के लिए कि क्या एक स्ट्रिंग दो अलग-अलग तारों का वैध फेरबदल है

इस उदाहरण में, हम जाँचेंगे कि क्या एक स्ट्रिंग जावा में दो अन्य तारों के वैध फेरबदल है।

इस उदाहरण को समझने के लिए, आपको निम्नलिखित जावा प्रोग्रामिंग विषयों का ज्ञान होना चाहिए:

  • जावा स्ट्रिंग
  • जावा जबकि और करते हैं … जबकि लूप

उदाहरण: जांचें कि क्या एक स्ट्रिंग दो अन्य तारों का एक वैध फेरबदल है

 class Main ( // check if result string is valid shuffle of string first and second static boolean shuffleCheck(String first, String second, String result) ( // check length of result is same as // sum of result of first and second if(first.length() + second.length() != result.length()) ( return false; ) // variables to track each character of 3 strings int i = 0, j = 0, k = 0; // iterate through all characters of result while (k != result.length()) ( // check if first character of result matches with first character of first string if (i < first.length() && first.charAt(i) == result.charAt(k)) i++; // check if first character of result matches the first character of second string else if (j < second.length() && second.charAt(j) == result.charAt(k)) j++; // if the character doesn't match else ( return false; ) // access next character of result k++; ) // after accessing all characters of result // if either first or second has some characters left if(i < first.length() || j < second.length()) ( return false; ) return true; ) public static void main(String() args) ( String first = "XY"; String second = "12"; String() results = ("1XY2", "Y12X"); // call the method to check if result string is // shuffle of the string first and second for (String result : results) ( if (shuffleCheck(first, second, result) == true) ( System.out.println(result + " is a valid shuffle of " + first + " and " + second); ) else ( System.out.println(result + " is not a valid shuffle of " + first + " and " + second); ) ) ) )

आउटपुट

 1 XY2 XY का एक वैध फेरबदल है और 12 Y12X XY और 12 का वैध फेरबदल नहीं है

उपरोक्त उदाहरण में, हमारे पास परिणाम नाम का एक स्ट्रिंग सरणी है। इसमें दो तार होते हैं: 1XY2 और Y12X। हम जांच कर रहे हैं कि क्या ये दो तार पहले (XY) और दूसरे (12) तार के वैध फेरबदल हैं।

यहां, प्रोग्राम कहता है कि 1XY2 XY और 12. का एक वैध फेरबदल है। हालांकि, Y12X एक वैध फेरबदल नहीं है।

ऐसा इसलिए है क्योंकि Y12X ने स्ट्रिंग XY के क्रम में बदलाव किया है। यहां, X से पहले Y का उपयोग किया जाता है। इसलिए, एक मान्य फेरबदल करने के लिए, स्ट्रिंग का क्रम बनाए रखा जाना चाहिए।

नोट : यदि दो तार के प्रारंभिक अक्षर मेल खाते हैं, तो कार्यक्रम भ्रमित हो जाता है। उदाहरण के लिए, यदि ab12 और abb34 दो तार हैं, तो abbab1234 एक वैध फेरबदल है।

हालांकि, कार्यक्रम पहले दो अक्षर का इलाज होगा अब पहली स्ट्रिंग के हिस्से के रूप। इसके कारण, तीसरा अक्षर b , पहले स्ट्रिंग (1) के तीसरे अक्षर और दूसरे स्ट्रिंग (a) के पहले अक्षर से मेल नहीं खाता है।

दिलचस्प लेख...