The easiest Java O(n) solution. With few lines of code and explanation


  • 0
    E
    String result = "";   //initialise the empty string
        if(nums.length == 2)  
            return   nums[0] + "/" + nums[1];
        if(nums.length == 1) return nums[0] + ""; //length == 1 
        for(int i=0; i<nums.length; i++){ //length > 2
            if( i == 0 ){                   
                    result += nums[0] + "/";  //the first element in the array
            }       
            else{
                if(i==1){
                        result += "(";  // insert the opening parentheses 
                }              
                if(i == nums.length-1){    // if it's the last element
                    result += nums[i] + ")";        // add it and close the parentheses 
                }else{
                     result += nums[i] + "/";  // concatenate the element and and add /
                }
                
            }
        }
        return result;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.